Salesforce Apex Developer Guide
Salesforce Apex Developer Guide
names and marks. Other marks appearing herein may be trademarks of their respective owners.
CONTENTS
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on the Salesforce Platform server, in conjunction with calls to the API. This guide introduces you to the Apex development
process and provides valuable information on learning, writing, deploying and testing Apex.
For reference information on Apex classes, interfaces, exceptions and so on, see Apex Reference Guide.
IN THIS SECTION:
Apex Release Notes
Use the Salesforce Release Notes to learn about the most recent updates and changes to Apex.
Getting Started with Apex
Learn about the Apex development lifecycle. Follow a step-by-step tutorial to create an Apex class and trigger, and deploy them to
a production organization.
Writing Apex
Apex is like Java for Salesforce. It enables you to add and interact with data in the Lightning Platform persistence layer. It uses classes,
data types, variables, and if-else statements. You can make it execute based on a condition, or have a block of code execute repeatedly.
Running Apex
You can access many features of the Salesforce user interface programmatically in Apex, and you can integrate with external SOAP
and REST Web services. You can run Apex code using a variety of mechanisms. Apex code runs in atomic transactions.
Debugging, Testing, and Deploying Apex
Develop your Apex code in a sandbox and debug it with the Developer Console and debug logs. Unit-test your code, then distribute
it to customers using packages.
Apex Reference
In Summer ’21 and later versions, Apex reference content is moved to a separate guide called the Apex Reference Guide.
Appendices
Glossary
1
Apex Developer Guide Introducing Apex
IN THIS SECTION:
Introducing Apex
Apex code is the first multitenant, on-demand programming language for developers interested in building the next generation of
business applications. Apex revolutionizes the way developers create on-demand applications.
Apex Development Process
In this chapter, you’ll learn about the Apex development lifecycle, and which organization and tools to use to develop Apex. You’ll
also learn about testing and deploying Apex code.
Apex Quick Start
This step-by-step tutorial shows how to create a simple Apex class and trigger, and how to deploy these components to a production
organization.
Introducing Apex
Apex code is the first multitenant, on-demand programming language for developers interested in building the next generation of
business applications. Apex revolutionizes the way developers create on-demand applications.
While many customization options are available through the Salesforce user interface, such as the ability to define new fields, objects,
workflow, and approval processes, developers can also use the SOAP API to issue data manipulation commands such as delete(),
update() or upsert(), from client-side programs.
These client-side programs, typically written in Java, JavaScript, .NET, or other programming languages, grant organizations more flexibility
in their customizations. However, because the controlling logic for these client-side programs is not located on Salesforce servers, they
are restricted by the performance costs of making multiple round-trips to the Salesforce site to accomplish common business transactions,
and by the cost and complexity of hosting server code, such as Java or .NET, in a secure and robust environment.
IN THIS SECTION:
1. What is Apex?
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on Salesforce servers in conjunction with calls to the API. Using syntax that looks like Java and acts like database stored
procedures, Apex enables developers to add business logic to most system events, including button clicks, related record updates,
and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects.
2. Understanding Apex Core Concepts
Apex code typically contains many things that you're familiar with from other programming languages.
3. When Should I Use Apex?
Salesforce provides the ability to customize prebuilt apps to fit your organization. For complex business processes, you can implement
custom functionality and user interfaces with a variety of tools, including Apex and Lightning Components.
4. How Does Apex Work?
All Apex runs entirely on-demand on the Lightning Platform. Developers write and save Apex code to the platform, and end users
trigger the execution of the Apex code via the user interface.
5. Developing Code in the Cloud
The Apex programming language is saved and runs in the cloud—the multitenant platform. Apex is tailored for data access and
data manipulation on the platform, and it enables you to add custom business logic to system events. While it provides many benefits
for automating business processes on the platform, it is not a general purpose programming language.
2
Apex Developer Guide Introducing Apex
What is Apex?
Apex is a strongly typed, object-oriented programming language that allows developers to execute
EDITIONS
flow and transaction control statements on Salesforce servers in conjunction with calls to the API.
Using syntax that looks like Java and acts like database stored procedures, Apex enables developers Available in: Salesforce
to add business logic to most system events, including button clicks, related record updates, and Classic (not available in all
Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects. orgs) and Lightning
Experience
3
Apex Developer Guide Introducing Apex
• Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject
records
• Looping that allows for bulk processing of multiple records at a time
• Locking syntax that prevents record update conflicts
• Custom public API calls that can be built from stored Apex methods
• Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex
Easy to use
Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax, loop syntax,
object and array notation. Where Apex introduces new elements, it uses syntax and semantics that are easy to understand and
encourage efficient use of the Lightning Platform. Therefore, 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 Salesforce server. Developers
use database stored procedures to thread together multiple transaction statements on a database server in a similar way. 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. It stores all custom field, object, and class dependencies in metadata to ensure that they
are not deleted while required by active Apex code.
Hosted
Apex is interpreted, executed, and controlled entirely by the Lightning Platform.
Multitenant aware
Like the rest of the Lightning Platform, Apex runs in a multitenant environment. So, the Apex runtime engine is designed to guard
closely against runaway code, preventing it from monopolizing shared resources. Any code that violates limits fails with
easy-to-understand error messages.
Easy to test
Apex provides built-in support for unit test creation and execution. It includes test results that indicate how much code is covered,
and which parts of your code could be more efficient. Salesforce ensures that all custom Apex code works as expected by executing
all unit tests prior to any platform upgrades.
Versioned
You can save your Apex code against different versions of the API. This enables you to maintain behavior.
Apex is included in Performance Edition, Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com.
4
Apex Developer Guide Introducing Apex
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 Salesforce Help.
5
Apex Developer Guide Introducing Apex
Tip: The semi-colon at the end of preceding codeblock is not optional. You must end all statements with a semi-colon.
In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This fact means that any changes
to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.
Non-primitive data type arguments, such as sObjects, are passed into methods by reference. Therefore, when the method returns, the
passed-in argument still references the same object as before the method call. Within the method, the reference can't be changed to
point to another object, but the values of the object's fields can be changed.
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 these 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
6
Apex Developer Guide Introducing Apex
A block is a series of statements that are grouped with curly braces and can be used in any place where a single statement is allowed.
For example:
if (true) {
System.debug(1);
System.debug(2);
} else {
System.debug(3);
System.debug(4);
}
In cases where a block consists of only one statement, the curly braces can be left off. For example:
if (true)
System.debug(1);
else
System.debug(2);
Using Collections
Apex has the following types of collections:
• Lists (arrays)
• Maps
• Sets
A list is a collection of elements, such as Integers, Strings, objects, or other collections. Use a list when the sequence of elements is
important. You can have duplicate elements in a list.
The first index position in a list is always 0.
To create a list:
• Use the new keyword
• Use the List keyword followed by the element type contained within <> characters.
Use the following syntax for creating a list:
The following example creates a list of Integer, and assigns it to the variable My_List. Remember, because Apex is strongly typed,
you must declare the data type of My_List as a list of Integer.
List<Integer> My_List = new List<Integer>();
7
Apex Developer Guide Introducing Apex
Set<datatype> set_name
[= new Set<datatype>();] |
[= new Set<datatype>{value [, value2. . .] };] |
;
The following example creates a set of String. The values for the set are passed in using the curly braces {}.
Set<String> My_String = new Set<String>{'a', 'b', 'c'};
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
8
Apex Developer Guide Introducing Apex
• While
• For
A Do-while loop checks the condition after the code has executed.
A While loop checks the condition at the start, before the code executes.
A For loop enables you to more finely control the condition used with the loop. In addition, Apex supports traditional For loops where
you set the conditions, as well as For loops that use lists and SOQL queries as part of the condition.
For more information, see Loops on page 56.
Apex
Use Apex if you want to:
• Create Web services.
• Create email services.
• Perform complex validation over multiple objects.
• Create complex business processes that aren’t supported by Flow Builder.
• Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object).
• Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed, regardless
of whether it originates in the user interface, a Visualforce page, or from SOAP API.
Lightning Components
Develop Lightning components to customize Lightning Experience, the Salesforce mobile app, or to build your own standalone apps.
You can also use out-of-the-box components to speed up development.
As of Spring ’19 (API version 45.0), you can build Lightning components using two programming models: the Lightning Web Components
model, and the original Aura Components model. Lightning web components are custom HTML elements built using HTML and modern
JavaScript. Lightning web components and Aura components can coexist and interoperate on a page. Configure Lightning web
components and Aura components to work in Lightning App Builder and Experience Builder. Admins and end users don’t know which
programming model was used to develop the components. To them, they’re simply Lightning components.
We recommend using the Lightning Web Components (LWC) model to create custom user interfaces. LWC follows W3C web standards,
and you can build and package components using standard JavaScript syntax. With LWC, you can work easily with Salesforce data using
Apex and Lightning Data Service.
For more information, see the LWC Dev Guide.
Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing
the Salesforce user interface. With Visualforce you can:
• Build wizards and other multistep processes.
• Create your own custom flow control through an application.
9
Apex Developer Guide Introducing Apex
• Define navigation patterns and data-specific rules for optimal, efficient application interaction.
For more information, see the Visualforce Developer's Guide.
SOAP API
Use standard SOAP API calls when you want to add functionality to a composite application that processes only one type of record at a
time and does not require any transactional control (such as setting a Savepoint or rolling back changes).
For more information, see the SOAP API Developer Guide.
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an abstract
set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata.
When an end user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform application
server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the
result. The end user observes no differences in execution time from standard platform requests.
Tip: All Apex code runs on the Lightning Platform, which is a shared resource used by all other organizations. To guarantee
consistent performance and scalability, the execution of Apex is bound by governor limits that ensure no single Apex execution
impacts the overall service of Salesforce. This means all Apex code is limited by the number of operations (such as DML or SOQL)
that it can perform within one process.
10
Apex Developer Guide Apex Development Process
All Apex requests return a collection that contains from 1 to 50,000 records. You cannot assume that your code only works on a
single record at a time. Therefore, you must implement programming patterns that take bulk processing into account. If you don’t,
you may run into the governor limits.
SEE ALSO:
Trigger and Bulk Request Best Practices
IN THIS SECTION:
What is the Apex Development Process?
To develop Apex, get a Developer Edition account, write and test your code, then deploy your code.
Choose a Salesforce Org for Apex Development
You can develop Apex in a sandbox, scratch org, or Developer Edition org, but not directly in a production org. With so many choices,
here’s some help to determine which org type is right for you and how to create it.
Choose a Development Environment for Writing Apex
There are several development environments for developing Apex code. Choose the environment that meets your needs.
Learning Apex
After you have your developer account, there are many resources available to you for learning about Apex
Writing Tests
Testing is the key to successful long-term development and is a critical component of the development process. We strongly
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
development.
Deploying Apex to a Sandbox Organization
Sandboxes create copies of your Salesforce org in separate environments. Use them for development, testing, and training without
compromising the data and applications in your production org. Sandboxes are isolated from your production org, so operations
that you perform in your sandboxes don’t affect your production org.
Deploy Apex to a Salesforce Production Organization
After you’ve finished all of your unit tests and verified that your Apex code is executing properly, the final step is deploying Apex to
your Salesforce production organization.
Adding Apex Code to a AppExchange App
You can include an Apex class or trigger in an app that you’re creating for AppExchange.
11
Apex Developer Guide Apex Development Process
Sandboxes (Recommended)
A sandbox is a copy of your production org’s metadata in a separate environment, with varying amounts of data depending on the
sandbox type. A sandbox provides a safe space for developers and admins to experiment with new features and validate changes before
deploying code to production. Developer and Developer Pro sandboxes with source tracking enabled can take advantage of many of
the features of our Salesforce DX source-driven development tools, including Salesforce CLI, Code Builder, and DevOps Center. See Create
a Sandbox in Salesforce Help.
12
Apex Developer Guide Apex Development Process
Developer Console
The Developer Console is an integrated development environment (IDE) built into Salesforce. Use it to create, debug, and test Apex
classes and triggers.
To open the Developer Console from Lightning Experience: Click the quick access menu ( ), then click Developer Console.
To open the Developer Console from Salesforce Classic: Click Your Name > Developer Console.
The Developer Console supports these tasks:
• Writing code—You can add code using the source code editor. Also, you can browse packages in your organization.
• Compiling code—When you save a trigger or class, the code is automatically compiled. Any compilation errors are reported.
• Debugging—You can view debug logs and set checkpoints that aid in debugging.
• Testing—You can execute tests of specific test classes or all tests in your organization, and you can view test results. Also, you can
inspect code coverage.
• Checking performance—You can inspect debug logs to locate performance bottlenecks.
• SOQL queries—You can query data in your organization and view the results using the Query Editor.
• Color coding and autocomplete—The source code editor uses a color scheme for easier readability of code elements and provides
autocompletion for class and method names.
Note: You can’t use the Salesforce Setup code editors to modify Apex in a Salesforce production org.
13
Apex Developer Guide Apex Development Process
Additional Editors
Alternatively, you can use any text editor, such as Notepad, to write Apex code. Then either copy and paste the code into your application,
or use one of the API calls to deploy it.
To develop an Apex IDE of your own, use SOAP API methods for compiling triggers and classes, and executing test methods. Use Metadata
API methods for deploying code to production environments. For more information, see Deploying Apex on page 696 and Using SOAP
API to Deploy Apex on page 702.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Learning Apex
After you have your developer account, there are many resources available to you for learning about Apex
14
Apex Developer Guide Apex Development Process
Training Courses
Training classes are also available from Salesforce Trailhead Academy. Grow and validate your skills with Salesforce Credentials.
Writing Tests
Testing is the key to successful long-term development and is a critical component of the development process. We strongly recommend
that you use a test-driven development process, that is, test development that occurs at the same time as code development.
To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are class
methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to
the database, and send no emails. Such methods are flagged with the @IsTest annotation in the method definition. Unit test methods
must be defined in test classes, that is, classes annotated with @IsTest.
Note: The @IsTest annotation on methods is equivalent to the testMethod keyword. As best practice, Salesforce
recommends that you use @IsTest rather than testMethod. The testMethod keyword may be versioned out in a future
release.
In addition, before you deploy Apex or package it for the AppExchange, the following must be true.
• Unit tests must cover at least 75% of your Apex code, and all of those tests must complete successfully.
Note the following.
– When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
– Calls to System.debug aren’t counted as part of Apex code coverage.
– Test methods and test classes aren’t counted as part of Apex code coverage.
– While only 75% of your Apex code must be covered by tests, don’t focus on the percentage of code that is covered. Instead,
make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single
records. This approach ensures that 75% or more of your code is covered by unit tests.
15
Apex Developer Guide Apex Quick Start
16
Apex Developer Guide Apex Quick Start
This Hello World sample requires custom objects. You can either create these objects on your own, or download the objects and Apex
code as an unmanaged package from AppExchange. To obtain the sample assets in your org, install the Apex Tutorials Package. This
package also contains sample code and objects for the Shipping Invoice example.
Note: There’s a more complex Shipping Invoice example that you can also walk through. That example illustrates many more
features of the language.
IN THIS SECTION:
1. Create a Custom Object
In this step, you create a custom object called Book with one custom field called Price.
2. Add an Apex Class
In this step, you add an Apex class that contains a method for updating the book price. This method is called by the trigger that
you’ll be adding in the next step.
3. Add an Apex Trigger
In this step, you create a trigger for the Book__c custom object that calls the applyDiscount method of the MyHelloWorld
class that you created in the previous step.
4. Add a Test Class
In this step, you add a test class with one test method. You also run the test and verify code coverage. The test method exercises
and validates the code in the trigger and class. Also, it enables you to reach 100% code coverage for the trigger and class.
5. Deploy Components to Production
In this step, you deploy the Apex code and the custom object you created previously to your production organization using change
sets.
17
Apex Developer Guide Apex Quick Start
11. Click Next to accept the default values for field-level security.
12. Click Save.
You've created a custom object called Book, and added a custom field to that custom object. Custom objects already have some standard
fields, like Name and CreatedBy, and allow you to add other fields that are more specific to your implementation. For this tutorial, the
Price field is part of our Book object, and the Apex class you’ll write in the next step accesses it.
SEE ALSO:
Salesforce Help: Find Object Management Settings
The previous code is the class definition to which you’ll be adding one method in the next step. Apex code is contained in classes.
This class is defined as public, which means the class is available to other Apex classes and triggers. For more information, see
Classes, Objects, and Interfaces on page 60.
3. Add this method definition between the class opening and closing brackets.
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
This method is called applyDiscount, and it’s both public and static. Because it’s a static method, you don't need to create an
instance of the class to access the method—you can use the name of the class followed by a dot (.) and the name of the method.
For more information, see Static and Instance Methods, Variables, and Initialization Code on page 68.
This method takes one parameter, a list of Book records, which is assigned to the variable books. Notice the __c in the object
name Book__c. This indicates that it’s a custom object that you created. Standard objects that are provided in the Salesforce
application, such as Account, don't end with this postfix.
The next section of code contains the rest of the method definition:
for (Book__c b :books){
b.Price__c *= 0.9;
}
Notice the __c after the field name Price__c. This indicates that it’s a custom field that you created. Standard fields that are
provided by default in Salesforce are accessed using the same type of dot notation but without the __c, for example, Name doesn't
18
Apex Developer Guide Apex Quick Start
end with __c in Book__c.Name. The statement b.Price__c *= 0.9; takes the old value of b.Price__c, multiplies
it by 0.9, which means its value is discounted by 10%, and then stores the new value into the b.Price__c field. The *= operator
is a shortcut. Another way to write this statement is b.Price__c = b.Price__c * 0.9;. See Expression Operators on
page 38.
4. Click Save to save the new class. You now have this full class definition.
public class MyHelloWorld {
public static void applyDiscount(Book__c[] books) {
for (Book__c b :books){
b.Price__c *= 0.9;
}
}
}
You now have a class that contains some code that iterates over a list of books and updates the Price field for each book. This code is
part of the applyDiscount static method called by the trigger that you’ll create in the next step.
MyHelloWorld.applyDiscount(books);
}
It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example, this
trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into the database.
The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context variable
called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and provide access
to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that are about to be inserted.
Book__c[] books = Trigger.new;
19
Apex Developer Guide Apex Quick Start
The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new books.
MyHelloWorld.applyDiscount(books);
You now have all the code that is needed to update the price of all books that get inserted. However, there’s still one piece of the puzzle
missing. Unit tests are an important part of writing code and are required. In the next step, you'll see why this is so and will be able to
add a test class.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Note: Testing is an important part of the development process. Before you can deploy Apex or package it for AppExchange, the
following must be true.
• Unit tests must cover at least 75% of your Apex code, and all of those tests must complete successfully.
Note the following.
– When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
– Calls to System.debug aren’t counted as part of Apex code coverage.
– Test methods and test classes aren’t counted as part of Apex code coverage.
– While only 75% of your Apex code must be covered by tests, don’t focus on the percentage of code that is covered. Instead,
make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and
single records. This approach ensures that 75% or more of your code is covered by unit tests.
1. From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes and click New.
2. In the class editor, add this test class definition, and then click Save.
@IsTest
private class HelloWorldTestClass {
@IsTest
static void validateHelloWorld() {
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;
20
Apex Developer Guide Apex Quick Start
This class is defined using the @IsTest annotation. Classes defined this way should only contain test methods and any methods
required to support those test methods. One advantage to creating a separate class for testing is that classes defined with @IsTest
don’t count against your org’s limit of 6 MB of Apex code. You can also add the @IsTest annotation to individual methods. For
more information, see @IsTest Annotation on page 102 and Execution Governors and Limits.
The method validateHelloWorld is defined using the @IsTest annotation. This annotation means that if changes are
made to the database, they’re rolled back when execution completes. You don’t have to delete any test data created in the test
method.
Note: The @IsTest annotation on methods is equivalent to the testMethod keyword. As best practice, Salesforce
recommends that you use @IsTest rather than testMethod. The testMethod keyword may be versioned out in a
future release.
First, the test method creates a book and inserts it into the database temporarily. The System.debug statement writes the value
of the price in the debug log.
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;
After the book is inserted, the code retrieves the newly inserted book, using the ID that was initially assigned to the book when it
was inserted. The System.debug statement then logs the new price that the trigger modified.
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);
When the MyHelloWorld class runs, it updates the Price__c field and reduces its value by 10%. The following test verifies
that the method applyDiscount ran and produced the expected result.
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);
3. To run this test and view code coverage information, switch to the Developer Console.
4. In the Developer Console, click Test > New Run.
5. To select your test class, click HelloWorldTestClass.
6. To add all methods in the HelloWorldTestClass class to the test run, click Add Selected.
7. Click Run.
The test result displays in the Tests tab. Optionally, you can expand the test class in the Tests tab to view which methods were run.
In this case, the class contains only one test method.
8. The Overall Code Coverage pane shows the code coverage of this test class. To view the percentage of lines of code in the trigger
covered by this test, which is 100%, double-click the code coverage line for HelloWorldTrigger. Because the trigger calls a method
from the MyHelloWorld class, this class also has coverage (100%). To view the class coverage, double-click MyHelloWorld.
21
Apex Developer Guide Apex Quick Start
9. To open the log file, in the Logs tab, double-click the most recent log line in the list of logs. The execution log displays, including
logging information about the trigger event, the call to the applyDiscount method, and the price before and after the trigger.
By now, you’ve completed all the steps necessary for writing some Apex code with a test that runs in your development environment.
In the real world, after you tested your code and are satisfied with it, you want to deploy the code and any prerequisite components to
a production org. The next step shows you how to do this deployment for the code and custom object you created.
SEE ALSO:
Salesforce Help: Open the Developer Console
22
Apex Developer Guide Writing Apex
In this tutorial, you learned how to create a custom object, how to add an Apex trigger, class, and test class. Finally, you also learned
how to test your code, and how to upload the code and the custom object using Change Sets.
Writing Apex
Apex is like Java for Salesforce. It enables you to add and interact with data in the Lightning Platform persistence layer. It uses classes,
data types, variables, and if-else statements. You can make it execute based on a condition, or have a block of code execute repeatedly.
IN THIS SECTION:
Data Types and Variables
Apex uses data types, variables, and related language constructs such as enums, constants, expressions, operators, and assignment
statements.
Control Flow Statements
Apex provides if-else statements, switch statements, and loops to control the flow of code execution. Statements are generally
executed line by line, in the order they appear. With control flow statements, you can make Apex code execute based on a certain
condition, or have a block of code execute repeatedly.
Working with Data in Apex
You can add and interact with data in the Lightning Platform persistence layer. The sObject data type is the main data type that
holds data objects. You’ll use Data Manipulation Language (DML) to work with data, and use query languages to retrieve data, such
as the (), among other things.
IN THIS SECTION:
1. Data Types
In Apex, all variables and expressions have a data type, such as sObject, primitive, or enum.
2. Primitive Data Types
Apex uses the same primitive data types as SOAP API, except for higher-precision Decimal type in certain cases. All primitive data
types are passed by value.
3. Collections
Collections in Apex can be lists, sets, or maps.
4. Enums
An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are
typically used to define a set of possible values that don’t otherwise have a numerical order. Typical examples include the suit of a
card, or a particular season of the year.
5. Variables
Local variables are declared with Java-style syntax. As with Java, multiple variables can be declared and initialized in a single statement.
6. Constants
Apex constants are variables whose values don’t change after being initialized once. Constants can be defined using the final
keyword.
23
Apex Developer Guide Data Types and Variables
Data Types
In Apex, all variables and expressions have a data type, such as sObject, primitive, or enum.
• A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types on page 24)
• An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c (see Working
with sObjects on page 126 in Chapter 4.)
• A collection, including:
– A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists on page
28)
– A set of primitives (see Sets on page 31)
– A map from a primitive to a primitive, sObject, or collection (see Maps on page 31)
• A typed list of values, also known as an enum (see Enums on page 33)
• Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces on page 60)
• Objects created from system supplied Apex classes
• Null (for the null constant, which can be assigned to any variable)
Methods can return values of any of the listed types, or return no value and be of type Void.
Type checking is strictly enforced at compile time. For example, the parser generates an error if an object field of type Integer is assigned
a value of type String. However, all compile-time exceptions are returned as specific fault codes, with the line number and column of
the error. For more information, see Debugging Apex on page 622.
24
Apex Developer Guide Data Types and Variables
Date A value that indicates a particular day. Unlike Datetime values, Date values contain no information
about time. Always create date values with a system static method.
You can add or subtract an Integer value from a Date value, returning a Date value. Addition and
subtraction of Integer values are the only arithmetic functions that work with Date values. You can’t
perform arithmetic functions that include two or more Date values. Instead, use the Date methods.
Use the String.valueOf() method to obtain the date without an appended timestamp.
Using an implicit string conversion with a Date value results in the date with the timestamp appended.
Datetime A value that indicates a particular day and time, such as a timestamp. Always create datetime values
with a system static method.
You can add or subtract an Integer or Double value from a Datetime value, returning a Date value.
Addition and subtraction of Integer and Double values are the only arithmetic functions that work
with Datetime values. You can’t perform arithmetic functions that include two or more Datetime
values. Instead, use the Datetime methods.
Decimal A number that includes a decimal point. Decimal is an arbitrary precision number. Currency fields
are automatically assigned the type Decimal.
If you don’t explicitly set the number of decimal places for a Decimal, the item from which the Decimal
is created determines the Decimal’s scale. Scale is a count of decimal places. Use the setScale
method to set a Decimal’s scale.
• If the Decimal is created as part of a query, the scale is based on the scale of the field returned
from the query.
• If the Decimal is created from a String, the scale is the number of characters after the decimal
point of the String.
• If the Decimal is created from a non-decimal number, the number is first converted to a String.
The scale is then set using the number of characters after the decimal point.
Note: Two Decimal objects that are numerically equivalent but differ in scale (such as 1.1
and 1.10) generally don’t have the same hashcode. Use caution when such Decimal objects
are used in Sets or as Map keys.
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 pi = 3.14159;
Double e = 2.7182818284D;
25
Apex Developer Guide Data Types and Variables
Integer A 32-bit number that doesn’t 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 doesn’t include a decimal point. Longs have a minimum value of -263 and a
maximum value of 263-1. Use this data type when you need a range of values wider than the range
provided by Integer. For example:
Long l = 2147483648L;
Object Any data type that is supported in Apex. Apex supports primitive data types (such as Integer),
user-defined custom classes, the sObject generic type, or an sObject specific type (such as Account).
All Apex data types inherit from Object.
You can cast an object that represents a more specific data type to its underlying data type. For
example:
Object obj = 10;
// Cast the object to an integer.
Integer i = (Integer)obj;
System.assertEquals(10, i);
The next example shows how to cast an object to a user-defined type—a custom Apex class named
MyApexClass that is predefined in your organization.
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
SOAP API: they can never be empty (only null), and they can never include leading and trailing
whitespace. These conventions are necessary for database storage.
Conversely, Strings in Apex can be null or empty and can include leading and trailing whitespace,
which can be used to construct a message.
The Solution sObject field SolutionNote operates as a special type of String. If you have HTML Solutions
enabled, any HTML tags used in this field are verified before the object is created or updated. If invalid
HTML is entered, an error is thrown. Any JavaScript used in this field is removed before the object is
26
Apex Developer Guide Data Types and Variables
In the following example, when the Solution displays on a detail page, the SolutionNote field only
contains HelloGoodbye:
trigger t2 on Solution (before insert) {
Trigger.new[0].SolutionNote =
'<javascript>Hello</javascript>Goodbye';
}
Time A value that indicates a particular time. Always create time values with a system static method. See
Time Class.
In addition, two non-standard primitive data types can’t 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 Lightning 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 can’t instantiate Currency in any other type of Apex.
For more information on the AnyType data type, see Field Types in the Object Reference for Salesforce.
SEE ALSO:
Expression Operators
27
Apex Developer Guide Data Types and Variables
Collections
Collections in Apex can be lists, sets, or maps.
Note: There is no limit on the number of items a collection can hold. However, there is a general limit on heap size.
IN THIS SECTION:
Lists
A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive
types, collections, sObjects, user-defined types, and built-in Apex types.
Sets
A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive
types, collections, sObjects, user-defined types, and built-in Apex types.
Maps
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive
types, collections, sObjects, user-defined types, and built-in Apex types.
Parameterized Typing
Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable before
that variable can be used.
SEE ALSO:
Execution Governors and Limits
Lists
A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types,
collections, sObjects, user-defined types, and built-in Apex types.
This table is a visual representation of a list of Strings:
28
Apex Developer Guide Data Types and Variables
To access elements in a list, use the List methods provided by Apex. For example:
List<Integer> myList = new List<Integer>(); // Define a new list
myList.add(47); // Adds a second element of value 47 to the end
// of the list
Integer i = myList.get(0); // Retrieves the element at index 0
myList.set(0, 1); // Adds the integer 1 to the list at index 0
myList.clear(); // Removes all elements from the list
For more information, including a complete list of all supported methods, see List Class.
To reference an element of a one-dimensional list, you can also follow the name of the list with the element's index position in square
brackets. For example:
colors[0] = 'Green';
Even though the size of the previous String array is defined as one element (the number between the brackets in new String[1]),
lists are elastic and can grow as needed provided that you use the List add method to add new elements. For example, you can
add two or more elements to the colors list. But if you’re using square brackets to add an element to a list, the list behaves like an
array and isn’t elastic, that is, you won’t be allowed to add more elements than the declared array size.
All lists are initialized to null. Lists can be assigned values and allocated memory using literal notation. For example:
Example Description
Defines an Integer list of size zero with no elements
List<Integer> ints = new Integer[0];
IN THIS SECTION:
List Sorting
You can sort list elements and the sort order depends on the data type of the elements.
List Sorting
You can sort list elements and the sort order depends on the data type of the elements.
29
Apex Developer Guide Data Types and Variables
Using the List.sort method, you can sort elements in a list. Sorting is in ascending order for elements of primitive data types, such
as strings. The sort order of other more complex data types is described in the chapters covering those data types.
You can sort custom types (your Apex classes) if they implement the Comparable interface. Alternatively, a class implementing the
Comparator interface can be passed as a parameter to the List.sort method. For more information on the sort order used for
sObjects, see Sorting Lists of sObjects.
This example shows how to sort a list of strings and verifies that the colors are in ascending order in the list.
List<String> colors = new List<String>{
'Yellow',
'Red',
'Green'};
colors.sort();
System.assertEquals('Green', colors.get(0));
System.assertEquals('Red', colors.get(1));
System.assertEquals('Yellow', colors.get(2));
For the Visualforce SelectOption control, sorting is in ascending order based on the value and label fields. See this next section for the
sequence of comparison steps used for SelectOption.
The output of the debug statements shows the contents of the list, both before and after the sort.
DEBUG|Before sorting: (System.SelectOption[value="A", label="United States",
disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"],
System.SelectOption[value="A", label="Mexico", disabled="false"])
DEBUG|After sorting: (System.SelectOption[value="A", label="Mexico", disabled="false"],
System.SelectOption[value="A", label="United States", disabled="false"],
System.SelectOption[value="C", label="Canada", disabled="false"])
30
Apex Developer Guide Data Types and Variables
Sets
A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive types,
collections, sObjects, user-defined types, and built-in Apex types.
This table represents a set of strings that uses city names:
Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers. A set can
contain up to seven levels of nested collections inside it, that is, up to eight levels overall.
To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
Set<String> myStringSet = new Set<String>();
The following example shows how to create a set with two hardcoded string values.
// Defines a new set with two elements
Set<String> set1 = new Set<String>{'New York', 'Paris'};
To access elements in a set, use the system methods provided by Apex. For example:
// Define a new set
Set<Integer> mySet = new Set<Integer>();
// Add two elements to the set
mySet.add(1);
mySet.add(3);
// Assert that the set contains the integer value we added
System.assert(mySet.contains(1));
// Remove the integer value from the set
mySet.remove(1);
The following example shows how to create a set from elements of another set.
// Define a new set that contains the
// elements of the set created in the previous example
Set<Integer> mySet2 = new Set<Integer>(mySet);
// Assert that the set size equals 1
// Note: The set from the previous example contains only one value
System.assert(mySet2.size() == 1);
For more information, including a complete list of all supported set system methods, see Set Class.
Note the following limitations on sets:
• Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example,
HashSet or TreeSet). Apex uses a hash structure for all sets.
• A set is an unordered collection—you can’t access a set element at a specific index. You can only iterate over set elements.
• The iteration order of set elements is deterministic, so you can rely on the order being the same in each subsequent execution of
the same code.
Maps
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive
types, collections, sObjects, user-defined types, and built-in Apex types.
31
Apex Developer Guide Data Types and Variables
Map keys and values can contain any collection, and can contain nested collections. For example, you can have a map of Integers to
maps, which, in turn, map Strings to lists. Map keys can contain up to seven levels of nested collections, that is, up to eight levels overall.
To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example:
Map<String, String> country_currencies = new Map<String, String>();
Map<ID, Set<String>> m = new Map<ID, Set<String>>();
You can use the generic or specific sObject data types with maps. You can also create a generic instance of a map.
As with lists, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the curly braces,
specify the key first, then specify the value for that key using =>. For example:
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' =>
'd'.toUpperCase()};
In the first example, the value for the key a is b, and the value for the key c is D.
To access elements in a map, use the Map methods provided by Apex. This example creates a map of integer keys and string values. It
adds two entries, checks for the existence of the first key, retrieves the value for the second entry, and finally gets the set of all keys.
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry'); // Insert a new key-value pair in the map
m.put(2, 'Second entry'); // Insert a new key-value pair in the map
System.assert(m.containsKey(1)); // Assert that the map contains a key
String value = m.get(2); // Retrieve a value, given a particular key
System.assertEquals('Second entry', value);
Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the
map
For more information, including a complete list of all supported Map methods, see Map Class.
Map Considerations
• Unlike Java, Apex developers don’t need to reference the algorithm that is used to implement a map in their declarations (for example,
HashMap or TreeMap). Apex uses a hash structure for all maps.
• The iteration order of map elements is deterministic. You can rely on the order being the same in each subsequent execution of the
same code. However, we recommend to always access map elements by key.
• A map key can hold the null value.
• Adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with the new
entry.
• Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding
distinct Map entries. Subsequently, the Map methods, including put, get, containsKey, and remove treat these keys as
distinct.
• Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods, which you provide in
your classes. Uniqueness of keys of all other non-primitive types, such as sObject keys, is determined by comparing the objects’ field
values. Use caution when you use an sObject as a map key because when the sObject is changed, it no longer maps to the same
32
Apex Developer Guide Data Types and Variables
Parameterized Typing
Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable before that
variable can be used.
This is legal in Apex:
Integer x = 1;
Lists, maps and sets are parameterized in Apex: they take any data type Apex supports for them as an argument. That data type must be
replaced with an actual data type upon construction of the list, map or set. For example:
List<String> myList = new List<String>();
Enums
An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are typically
used to define a set of possible values that don’t otherwise have a numerical order. Typical examples include 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. Hiding the implementation prevents
any possible misuse of the values to perform arithmetic and so on. After you create an enum, variables, method arguments, and return
types can be declared of that type.
33
Apex Developer Guide Data Types and Variables
Note: Unlike Java, the enum type itself has no constructor syntax.
To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values. For example,
the following code creates an enum called Season:
public enum Season {WINTER, SPRING, SUMMER, FALL}
By creating the enum Season, you have also created a new data type called Season. You can use this new data type as you would
any other data type. For example:
Season southernHemisphereSeason = Season.WINTER;
You can also define a class as an enum. When you create an enum class, do not use the class keyword in the definition.
public enum MyEnumClass { X, Y }
You can use an enum in any place you can use another data type name. If you define a variable whose type is an enum, any object you
assign to it must be an instance of that enum class.
Any webservice method can use enum types as part of their signature. In this case, the associated WSDL file includes definitions
for the enum and its values, which the API client can use.
Apex provides the following system-defined enums:
• System.StatusCode
This enum corresponds to the API error code that is exposed in the WSDL document for all API operations. For example:
StatusCode.CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY
StatusCode.INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY
The full list of status codes is available in the WSDL file for your organization. For more information about accessing the WSDL file
for your organization, see Downloading Salesforce WSDLs and Client Authentication Certificates in Salesforce Help.
• System.XmlTag:
This enum returns a list of XML tags used for parsing the result XML from a webservice method. For more information, see
XmlStreamReader Class.
• System.RoundingMode:
This enum is used by methods that perform mathematical operations to specify the rounding behavior for the operation. Typical
examples are the Decimal divide method and the Double round method. For more information, see Rounding Mode.
• System.SoapType:
This enum is returned by the field describe result getSoapType method. For more information, see SOAPType Enum.
34
Apex Developer Guide Data Types and Variables
• System.DisplayType:
This enum is returned by the field describe result getType method. For more information, see DisplayType Enum.
• System.JSONToken:
This enum is used for parsing JSON content. For more information, see JsonToken Enum.
• ApexPages.Severity:
This enum specifies the severity of a Visualforce message. For more information, see ApexPages.Severity Enum.
• Dom.XmlNodeType:
This enum specifies the node type in a DOM document.
All enum values, including system enums, have common methods associated with them. For more information, see Enum Methods.
You cannot add user-defined methods to enum values.
Variables
Local variables are declared with Java-style syntax. As with Java, multiple variables can be declared and initialized in a single statement.
Local variables are declared with Java-style syntax. For example:
Integer i = 0;
String str;
List<String> strList;
Set<String> s;
Map<ID, String> m;
As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
Integer i, j, k;
Many instance methods on the data type will fail if the variable is null. In this example, the second statement generates an exception
(NullPointerException)
Date d;
d.addDays(2);
All variables are initialized to null if they aren’t assigned a value. For instance, in the following example, i, and k are assigned values,
while the integer variable j and the boolean variable b are set to null because they aren’t explicitly initialized.
Integer i = 0, j, k = 1;
Boolean b;
35
Apex Developer Guide Data Types and Variables
Note: A common pitfall is to assume that an uninitialized boolean variable is initialized to false by the system. This isn’t the
case. Like all other variables, boolean variables are null if not assigned a value explicitly.
Variable Scope
Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks can’t redefine a variable name
that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:
Integer i;
{
// Integer i; This declaration is not allowed
}
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;
Note: You’ll learn more about sObjects, SOQL, and SOSL later in this guide.
Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the SOAP API and the Salesforce
user interface. The use of these semantics can lead to some interesting behavior. For example, if an end-user generates a report based
on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned in the result. The rationale for this
behavior is that users typically think of a field without a value as just a space character, rather than its actual null value. Consequently,
in Apex, the following expressions all evaluate to true:
String s;
System.assert('a' == 'A');
System.assert(s < 'b');
System.assert(!(s > 'b'));
Note: Although s < 'b' evaluates to true in the example above, 'b.'compareTo(s) generates an error because
you’re trying to compare a letter to a null value.
Constants
Apex constants are variables whose values don’t change after being initialized once. Constants can be defined using the final keyword.
36
Apex Developer Guide Data Types and Variables
The final keyword means that the variable can be assigned at most once, either in the declaration itself, or with a static initializer
method if the constant is defined in a class. This example declares two constants. The first is initialized in the declaration statement. The
second is assigned a value in a static block by calling a static method.
public class myCls {
static final Integer PRIVATE_INT_CONST = 200;
static final Integer PRIVATE_INT_CONST2;
static {
PRIVATE_INT_CONST2 = calculate();
}
}
For more information, see Using the final Keyword on page 84.
IN THIS SECTION:
Expressions
An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value.
Expression Operators
Expressions can be joined to one another with operators to create compound expressions.
Safe Navigation Operator
Use the safe navigation operator (?.) to replace explicit, sequential checks for null references. This operator short-circuits expressions
that attempt to operate on a null value and returns null instead of throwing a NullPointerException.
Null Coalescing Operator
The ?? operator returns the left-hand argument if the left-hand argument isn’t null. Otherwise, it returns the right-hand argument.
Similar to the safe navigation operator (?.), the null coalescing operator (??) replaces verbose and explicit checks for null references
in code.
Operator Precedence
Operators are interpreted in order, according to rules.
Comments
Both single and multiline comments are supported in Apex code.
SEE ALSO:
Expanding sObject and List Expressions
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:
37
Apex Developer Guide Data Types and Variables
• 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
• A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example:
Account[] aa = [SELECT Id, Name FROM Account WHERE Name ='Acme'];
Integer i = [SELECT COUNT() FROM Contact WHERE LastName ='Weissman'];
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name),
Contact, Opportunity, Lead];
Expression Operators
Expressions can be joined to one another with operators to create compound expressions.
Apex supports the following operators:
38
Apex Developer Guide Data Types and Variables
&= x &= y AND assignment operator (Right associative). If x, a Boolean, and y, a Boolean,
are both true, then x remains true. Otherwise x is assigned the value of false. x
and y can’t be null.
<<= x <<= y Bitwise shift left assignment operator. Shifts each bit in x to the left by y bits
so that the high-order bits are lost and the new right bits are set to 0. This value is
then reassigned to x.
>>= x >>= y Bitwise shift right signed assignment operator. Shifts each bit in x to the right
by y bits so that the low-order bits are lost and the new left bits are set to 0 for
positive values of y and 1 for negative values of y. This value is then reassigned to
x.
>>>= x >>>= y Bitwise shift right unsigned assignment operator. Shifts each bit in x to the
right by y bits so that the low-order bits are lost and the new left bits are set to 0
for all values of y. This value is then reassigned to x.
39
Apex Developer Guide Data Types and Variables
== x == y Equality operator. If the value of x equals the value of y, the expression evaluates
to true. Otherwise the expression evaluates to false.
Note:
• Unlike Java, == in Apex compares object value equality not reference
equality, except for user-defined types. Therefore:
– String comparison using == is case-insensitive and is performed
according to the locale of the context user
– ID comparison using == is case-sensitive and doesn’t distinguish
between 15-character and 18-character formats
– User-defined types are compared by reference, which means that
two objects are equal only if they reference the same location in
memory. You can override this default comparison behavior by
providing equals and hashCode methods in your class to
compare object values instead.
• For sObjects and sObject arrays, == performs a deep check of all sObject
field values before returning its result. Likewise for collections and built-in
Apex objects.
• For records, every field must have the same value for == to evaluate to
true.
• x or y can be the literal null.
• The comparison of any two values can never result in null.
• SOQL and SOSL use = for their equality operator and not ==. Although
Apex and SOQL and SOSL are strongly linked, this unfortunate syntax
discrepancy exists because most modern languages use = for assignment
40
Apex Developer Guide Data Types and Variables
=== x === y Exact equality operator. If x and y reference the exact same location in memory
the expression evaluates to true. Otherwise the expression evaluates to false.
< x < y Less than operator. If x is less than y, the expression evaluates to true. Otherwise
the expression evaluates to false.
Note:
• Unlike other database stored procedures, Apex doesn’t 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 can’t be Booleans.
• The comparison of two strings is performed according to the locale of
the context user and is case-insensitive.
> x > y Greater than operator. If x is greater than y, the expression evaluates to true.
Otherwise the expression evaluates to false.
Note:
• The comparison of any two values can never result in null.
• If x or y equal null and are Integers, Doubles, Dates, or Datetimes,
the expression is false.
• A non-null String or ID value is always greater than a null value.
• If x and y are IDs, they must reference the same type of object.
Otherwise a runtime error results.
• 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 can’t be Booleans.
• The comparison of two strings is performed according to the locale of
the context user and is case-insensitive.
41
Apex Developer Guide Data Types and Variables
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 can’t be Booleans.
• The comparison of two strings is performed according to the locale of
the context user and is case-insensitive.
>= x >= y Greater than or equal to operator. If x is greater than or equal to y, the
expression evaluates to true. Otherwise the expression evaluates to false.
Note:
• The comparison of any two values can never result in null.
• If x or y equal null and are Integers, Doubles, Dates, or Datetimes,
the expression is false.
• A non-null String or ID value is always greater than a null value.
• If x and y are IDs, they must reference the same type of object.
Otherwise a runtime error results.
• If x or y is an ID and the other value is a String, the String value is
validated and treated as an ID.
• x and y can’t be Booleans.
• The comparison of two strings is performed according to the locale of
the context user and is case-insensitive.
!= x != y Inequality operator. If the value of x doesn’t equal the value of y, the expression
evaluates to true. Otherwise the expression evaluates to false.
Note:
• String comparison using != is case-insensitive
• Unlike Java, != in Apex compares object value equality not reference
equality, except for user-defined types.
• For sObjects and sObject arrays, != performs a deep check of all sObject
field values before returning its result.
• For records, != evaluates to true if the records have different values for
any field.
42
Apex Developer Guide Data Types and Variables
!== x !== y Exact inequality operator. If x and y don’t reference the exact same location in
memory, the expression evaluates to true. Otherwise the expression evaluates to
false.
! !x Logical complement operator. Inverts the value of a Boolean so that true becomes
false and false becomes true.
43
Apex Developer Guide Data Types and Variables
-- x-- Decrement operator. Subtracts 1 from the value of x, a variable of a numeric type.
--x If prefixed (--x), the expression evaluates to the value of x after the decrement. If
postfixed (x--), the expression evaluates to the value of x before the decrement.
& x & y Bitwise AND operator. ANDs each bit in x with the corresponding bit in y so
that the result bit is set to 1 if both of the bits are set to 1.
| x | y Bitwise OR operator. ORs each bit in x with the corresponding bit in y so that
the result bit is set to 1 if at least one of the bits is set to 1.
^ x ^ y Bitwise exclusive OR operator. Exclusive ORs each bit in x with the corresponding
bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the
other bit is set to 0.
^= x ^= y Bitwise exclusive OR operator. Exclusive ORs each bit in x with the corresponding
bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the
other bit is set to 0. Assigns the result of the exclusive OR operation to x.
<< x << y Bitwise shift left operator. Shifts each bit in x to the left by y bits so that the
high-order bits are lost and the new right bits are set to 0.
>> x >> y Bitwise shift right signed operator. Shifts each bit in x to the right by y bits so
that the low-order bits are lost and the new left bits are set to 0 for positive values
of y and 1 for negative values of y.
>>> x >>> y Bitwise shift right unsigned operator. Shifts each bit in x to the right by y bits
so that the low-order bits are lost and the new left bits are set to 0 for all values of
y.
Important: Where possible, we changed noninclusive terms to align with our company value of Equality. We maintained certain
terms to avoid any effect on customer implementations.
44
Apex Developer Guide Data Types and Variables
If the left-hand-side of the chain expression evaluates to null, the right-hand-side isn’t evaluated. Use the safe navigation operator (?.)
in method, variable, and property chaining. The part of the expression that isn’t evaluated can include variable references, method
references, or array expressions.
Note: All Apex types are implicitly nullable and can hold a null value returned from the operator.
Examples
• This example first evaluates a, and returns null if a is null. Otherwise the return value is a.b.
a?.b // Evaluates to: a == null ? null : a.b
• This example returns null if a[x] evaluates to null. If a[x] doesn’t evaluate to null and aMethod() returns null, then this
expression throws a NullPointerException.
a[x]?.aMethod().aField // Evaluates to null if a[x] == null
• This example indicates that the type of the expression is the same whether the safe navigation operator is used in the expression or
not.
Integer x = anObject?.anIntegerField; // The expression is of type Integer because the
field is of type Integer
• This example shows a single statement replacing a block of code that checks for nulls.
// Previous code checking for nulls
String profileUrl = null;
if (user.getProfileUrl() != null) {
profileUrl = user.getProfileUrl().toExternalForm();
}
• This example shows a single-row SOQL query using the safe navigation operator.
// Previous code checking for nulls
results = [SELECT Name FROM Account WHERE Id = :accId];
if (results.size() == 0) { // Account was deleted
return null;
}
return results[0].Name;
45
Apex Developer Guide Data Types and Variables
is equivalent to:
T ref = null;
if (a1 != null) {
ref = (T)a1.b1;
}
result = ref.c1();
SOQL Queries String s = [SELECT LastName If the SOQL query returns no objects, then
FROM Contact]?.LastName; the expression evaluates to null. The
behavior is equivalent to:
List<Contact> contacts =
[SELECT LastName FROM
Contact];
String s;
if (contacts.size() == 0) {
46
Apex Developer Guide Data Types and Variables
You can’t use the Safe Navigation Operator in certain cases. Attempting to use the operator in these ways causes an error during
compilation:
• Types and static expressions with dots. For example:
– Namespaces
– {Namespace}.{Class}
– Trigger.new
– Flow.interview.{flowName}
– {Type}.class
Note: You can use the operator with addError() on SObjects, including lookup and master-detail fields.
47
Apex Developer Guide Data Types and Variables
While using the null coalescing operator, always keep operator precedence in mind. In some cases, using parentheses is necessary to
obtain the desired results. For example, the expression top ?? 100 - bottom ?? 0 evaluates to top ?? (100 - bottom
?? 0) and not to (top ?? 100) - (bottom ?? 0).
Apex supports assignment of a single resultant record from a SOQL query, but throws an exception if there are no rows returned by the
query. The null coalescing operator can be used to gracefully deal with the case where the query doesn’t return any rows. If a SOQL
query is used as the left-hand operand of the operator and rows are returned, then the null coalescing operator returns the query results.
If no rows are returned, the null coalescing operator returns the right-hand operand.
Warning: Salesforce recommends against using multiple SOQL queries in a single statement that also uses the null coalescing
operator.
These examples work with Account objects.
Account defaultAccount = new Account(name = 'Acme');
// Left operand SOQL is empty, return defaultAccount from right operand:
Account a = [SELECT Id FROM Account
WHERE Id = '001000000FAKEID'] ?? defaultAccount;
Assert.areEqual(defaultAccount, a);
// If there isn't a matching Account or the Billing City is null, replace the value
string city = [Select BillingCity
From Account
Where Id = '001xx000000001oAAA']?.BillingCity;
System.debug('Matches count: ' + city?.countMatches('San Francisco') ?? 0 );
Usage
There are some restrictions on using the null coalescing operator.
• You can’t use the null coalescing operator as the left side of an assignment operator in an assignment.
– foo??bar = 42;// This is not a valid assignment
– foo??bar++; // This is not a valid assignment
SEE ALSO:
Apex Developer Guide: Operator Precedence
Operator Precedence
Operators are interpreted in order, according to rules.
48
Apex Developer Guide Data Types and Variables
2 ~ ! -x +x (type) new Unary operators, additive operators, type cast and object
creation
6 < <= > >= instanceof Greater-than and less-than comparisons, reference tests
9 ^ Bitwise XOR
10 | Bitwise OR
12 || Logical OR
13 ?? Null Coalescing
14 ?: Ternary
Comments
Both single and multiline comments are supported in Apex code.
• To create a single line comment, use //. All characters on the same line to the right of the // are ignored by the parser. For example:
Integer i = 1; // This comment is ignored by the parser
• To create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. For example:
Integer i = 1; /* This comment can wrap over multiple
lines without getting interpreted by the
parser. */
Assignment Statements
An assignment statement is any statement that places a value into a variable.
An assignment statement generally takes one of two forms:
[LValue] = [new_value_expression];
[LValue] = [[inline_soql_query]];
49
Apex Developer Guide Data Types and Variables
In the forms above, [LValue] stands for any expression that can be placed on the left side of an assignment operator. These include:
• A simple variable. For example:
Integer i = 1;
Account a = new Account();
Account[] accts = [SELECT Id FROM Account];
• An sObject field reference that the context user has permission to edit. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
// 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:
Account[] a = new Account[]{new Account()};
Account[] b = a;
a[0].Name = 'Acme';
System.assert(b[0].Name == 'Acme');
In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Expression Operators on page 38.
50
Apex Developer Guide Data Types and Variables
Rules of Conversion
In general, Apex requires you to explicitly convert one data type to another. For example, a variable of the Integer data type cannot be
implicitly converted to a String. You must use the string.format method. However, a few data types can be implicitly converted,
without using a method.
Numbers form a hierarchy of types. Variables of lower numeric types can always be assigned to higher types without explicit conversion.
The following is the hierarchy for numbers, from lowest to highest:
1. Integer
2. Long
3. Double
4. Decimal
Note: Once a value has been passed from a number of a lower type to a number of a higher type, the value is converted to the
higher type of number.
Note that the hierarchy and implicit conversion is unlike the Java hierarchy of numbers, where the base interface number is used and
implicit object conversion is never allowed.
In addition to numbers, other data types can be implicitly converted. The following rules apply:
• IDs can always be assigned to Strings.
• Strings can be assigned to IDs. However, at runtime, the value is checked to ensure that it is a legitimate ID. If it is not, a runtime
exception is thrown.
• The instanceOf keyword can always be used to test whether a string is an ID.
51
Apex Developer Guide Control Flow Statements
overflow occurs. The following example shows how to correctly compute the amount of milliseconds in a year by multiplying Long
numeric values.
Long MillsPerYear = 365L * 24L * 60L * 60L * 1000L;
Long ExpectedValue = 31536000000L;
System.assertEquals(MillsPerYear, ExpectedValue);
IN THIS SECTION:
Conditional (If-Else) Statements
The conditional statement in Apex works similarly to Java.
Switch Statements
Apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly.
Loops
Apex supports five types of procedural loops.
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
52
Apex Developer Guide Control Flow Statements
if (x <= 0) {
if (x == 0) {
sign = 0;
} else {
sign = -1;
}
}
Switch Statements
Apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly.
The syntax is:
switch on expression {
when value1 { // when block 1
// code block 1
}
when value2 { // when block 2
// code block 2
}
when value3 { // when block 3
// code block 3
}
when else { // default block, optional
// code block 4
}
}
The when value can be a single value, multiple values, or sObject types. For example:
when value1 {
}
The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, the
when else code block is executed. If there isn’t a when else block, no action is taken.
53
Apex Developer Guide Control Flow Statements
Note: There is no fall-through. After the code block is executed, the switch statement exits.
When Blocks
Each when block has a value that the expression is matched against. These values can take one of the following forms.
• when literal {} (a when block can have multiple, comma-separated literal clauses)
• when SObjectType identifier {}
• when enum_value {}
The value null is a legal value for all types.
Each when value must be unique. For example, you can use the literal x only in one when block clause. A when block is matched
one time at most.
Note: Salesforce recommends including a when else block, especially with enum types, although it isn’t required. When you
build a switch statement using enum values provided by a managed package, your code might not behave as expected if a
new version of the package contains additional enum values. You can prevent this problem by including a when else block
to handle unanticipated values.
If you include a when else block, it must be the last block in the switch statement.
54
Apex Developer Guide Control Flow Statements
Method Example
Instead of switching on a variable expression, the following example switches on the result of a method call.
switch on someInteger(i) {
when 2 {
System.debug('when block 2');
}
when 3 {
System.debug('when block 3');
}
when else {
System.debug('default');
}
}
55
Apex Developer Guide Control Flow Statements
You can replace and simplify this code with the following switch statement.
switch on sobject {
when Account a {
System.debug('account ' + a);
}
when Contact c {
System.debug('contact ' + c);
}
when null {
System.debug('null');
}
when else {
System.debug('default');
}
}
Note: You can use only one sObject type per when block.
Loops
Apex supports five types of procedural loops.
56
Apex Developer Guide Control Flow Statements
IN THIS SECTION:
1. Do-While Loops
2. While Loops
3. For 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.
57
Apex Developer Guide Control Flow Statements
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:
• The traditional for loop:
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.
IN THIS SECTION:
Traditional For Loops
List or Set Iteration for Loops
Iterating Collections
58
Apex Developer Guide Control Flow Statements
When executing this type of for loop, the Apex runtime engine performs the following steps, in order:
1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this statement.
2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits.
3. Execute the code_block.
4. Execute the increment_stmt statement.
5. Return to Step 2.
As an example, the following code outputs the numbers 1 - 10 into the debug log. Note that an additional initialization variable, j, is
included to demonstrate the syntax:
for (Integer i = 0, j = 0; i < 10; i++) {
System.debug(i+1);
}
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.
59
Apex Developer Guide Classes, Objects, and Interfaces
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.
IN THIS SECTION:
1. 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.
2. Interfaces
An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body
of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained
in the interface.
3. Keywords
Apex provides the keywords final, instanceof, super, this, transient, with sharing and without
sharing.
4. Annotations
An Apex annotation modifies the way that a method or class is used, similar to annotations in Java. Annotations are defined with
an initial @ symbol, followed by the appropriate keyword.
5. Classes and Casting
In general, all type information is available at run time. This means that Apex enables casting, that is, a data type of one class can be
assigned to a data type of another class, but only if one class is a subclass of the other class. Use casting when you want to convert
an object from one data type to another.
6. Differences Between Apex Classes and Java Classes
Apex classes and Java classes work in similar ways, but there are some significant differences.
7. Class Definition Creation
Use the class editor to create a class in Salesforce.
8. Namespace Prefix
The Salesforce application supports the use of namespace prefixes. Namespace prefixes are used in managed AppExchange packages
to differentiate custom object and field names from names used by other organizations.
9. Apex Code Versions
To aid backwards-compatibility, classes and triggers are stored with the version settings for a specific Salesforce API version.
10. Lists of Custom Types and Sorting
Lists can hold objects of your user-defined types (your Apex classes). Lists of user-defined types can be sorted.
60
Apex Developer Guide Classes, Objects, and Interfaces
Classes
As in Java, you can create classes in Apex. A class is a template or blueprint from which objects are created. An object is an instance of a
class.
For example, the PurchaseOrder class describes an entire purchase order, and everything that you can do with a purchase order.
An instance of the PurchaseOrder class is a specific purchase order that you send or receive.
All objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. The state of a
PurchaseOrder object—what it knows—includes the user who sent it, the date and time it was created, and whether it was flagged as
important. The behavior of a PurchaseOrder object—what it can do—includes checking inventory, shipping a product, or notifying a
customer.
A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or Type.
Since these variables are associated with a class and are members of it, they are commonly referred to as member variables. Methods
are used to control behavior, such as getOtherQuotes or copyLineItems.
A class can contain other classes, exception types, and initialization code.
An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of
each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the
interface.
For more general information on classes, objects, and interfaces, see http://java.sun.com/docs/books/tutorial/java/concepts/index.html
In addition to classes, Apex provides triggers, similar to database triggers. A trigger is Apex code that executes before or after database
operations. See Triggers.
IN THIS SECTION:
1. Apex Class Definition
2. Class Variables
3. Class Methods
4. Using Constructors
5. Access Modifiers
6. Static and Instance Methods, Variables, and Initialization Code
In Apex, you can have static methods, variables, and initialization code. However, Apex classes can't be static. You can also have
instance methods, member variables, and initialization code, which have no modifiers, and local variables.
7. Apex Properties
8. Extending a Class
You can extend a class to provide more specialized behavior.
9. Extended Class Example
61
Apex Developer Guide Classes, Objects, and Interfaces
Note: Avoid using standard object names for class names. Doing so causes unexpected results. For a list of standard objects, see
Object Reference for Salesforce.
Use the following syntax for defining classes:
private | public | global
[virtual | abstract | with sharing | without sharing]
class ClassName [implements InterfaceNameList] [extends ClassName]
{
// The body of the class
}
• The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the default
access for inner classes—that is, if you don't specify an access modifier for an inner class, it’s considered private. This keyword
can only be used with inner classes (or with top-level test classes marked with the @IsTest annotation).
• The public access modifier declares that this class is visible in your application or namespace.
• The global access modifier declares that this class is known by all Apex code everywhere. All classes containing 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, without sharing, and inherited sharing Keywords on page 87.
• The virtual definition modifier declares that this class allows extension and overrides. You can’t override a method with the
override keyword unless the class has been defined as virtual.
• The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature
declared and no body defined.
Note:
• You can’t add an abstract method to a global class after the class has been uploaded in a Managed - Released package version.
• If the class in the Managed - Released package is virtual, the method that you can add to it must also be virtual and must have
an implementation.
62
Apex Developer Guide Classes, Objects, and Interfaces
• You can’t override a public or protected virtual method of a global class of an installed managed package.
For more information about managed packages, see What is a Package? on page 703.
A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex doesn’t support multiple
inheritance. The interface names in the list are separated by commas. For more information about interfaces, see Interfaces on page 80.
For more information about method and variable access modifiers, see Access Modifiers on page 67.
SEE ALSO:
Documentation Typographical Conventions
Salesforce Help: Manage Apex Classes
Salesforce Help: Developer Console Functionality
Class Variables
To declare a variable, specify the following:
• Optional: Modifiers, such as public or final, as well as static.
• Required: The data type of the variable, such as String or Boolean.
• Required: The name of the variable.
• Optional: The value of the variable.
Use the following syntax when defining a variable:
For example:
private static final Integer MY_INT;
private final Integer i = 1;
Class Methods
To define a method, specify the following:
• Optional: Modifiers, such as public or protected.
63
Apex Developer Guide Classes, Objects, and Interfaces
• Required: The data type of the value returned by the method, such as String or Integer. Use void if the method doesn’t return a
value.
• Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in parentheses
(). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters.
• Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable declarations, is
contained here.
Use the following syntax when defining a method:
Note: You can use override to override methods only in classes that have been defined as virtual or abstract.
For example:
public static Integer getInt() {
return MY_INT;
}
As in Java, methods that return values can also be run as a statement if their results aren’t assigned to another variable.
User-defined methods:
• Can be used anywhere that system methods are used.
• Can be recursive.
• Can have side effects, such as DML insert statements that initialize sObject record IDs. See Apex DML Statements.
• 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 aren’t needed.
• Can be overloaded. For example, a method named example 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 can’t find an exact match, it then seeks an approximate match using type
coercion rules. For more information on data conversion, see Rules of Conversion on page 51.
Note: If the parser finds multiple approximate matches, a parse-time exception is generated.
• Methods with a void return type are typically invoked as a standalone statement in Apex code. For example:
System.debug('Here is a note for the log.');
• Can have statements where the return values are run as a statement if their results aren’t assigned to another variable. This rule is
the same in Java.
64
Apex Developer Guide Classes, Objects, and Interfaces
The following are examples of passing primitive and non-primitive data type arguments into methods.
Example: Passing Primitive Data Type Arguments
This example shows how a primitive argument of type String is passed by value into another method. The debugStatusMessage
method in this example creates a String variable, msg, and assigns it a value. It then passes this variable as an argument to another
method, which modifies the value of this String. However, since String is a primitive type, it’s passed by value, and when the method
returns, the value of the original variable, msg, is unchanged. An assert statement verifies that the value of msg is still the old value.
public class PassPrimitiveTypeExample {
public static void debugStatusMessage() {
String msg = 'Original value';
processString(msg);
// The value of the msg variable didn't
// change; it is still the old value.
System.assertEquals(msg, 'Original value');
}
65
Apex Developer Guide Classes, Objects, and Interfaces
m.add(75);
m.add(80);
m.add(82);
}
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, a default, no-argument, public constructor is used.
The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return type and
it is not inherited by the object created from it.
After you write the constructor for a class, you must use the new keyword in order to instantiate an object from that class, using that
constructor. For example, using the following class:
public class TestObject {
A new object of this type can be instantiated with the following code:
TestObject myTest = new TestObject();
If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments.
If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must create your own
no-argument constructor in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument
public constructor.
In Apex, a constructor can be overloaded, that is, there can be more than one constructor for a class, each having different parameters.
The following example illustrates a class with two constructors: one with no arguments and one that takes a simple Integer argument.
It also illustrates how one constructor calls another constructor using the this(...) syntax, also know as constructor chaining.
public class TestObject2 {
Integer size;
66
Apex Developer Guide Classes, Objects, and Interfaces
New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(42);
TestObject2 myObject2 = new TestObject2();
Every constructor that you create for a class must have a different argument list. In the following example, all of the constructors are
possible:
public class Leads {
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 aren’t as useful in smaller portions of Apex. For example,
declaring a method as global in an anonymous block doesn’t enable you to call it from outside of that code.
For more information on class access modifiers, see Apex Class Definition on page 62.
Note: Methods defined in an interface have the same access modifier as the interface (public or global). For more information,
see Interfaces.
By default, a method or variable is visible only to the Apex code within the defining class. Explicitly specify a method or variable as public
in order for it to be available to other classes in the same application namespace (see Namespace Prefix). You can change the level of
visibility by using the following access modifiers:
67
Apex Developer Guide Classes, Objects, and Interfaces
private
This access modifier is the default, and means that the method or variable is accessible only within the Apex class in which it’s defined.
If you don’t specify an access modifier, the method or variable is private.
protected
This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the
defining Apex class. You can only use this access modifier for instance methods and member variables. This setting is strictly more
permissive than the default (private) setting, just like Java.
public
This means that the method or variable is accessible by all Apex within a specific package. For accessibility by all second-generation
(2GP) managed packages that share a namespace, use public with the @NamespaceAccessible annotation. Using the
public access modifier in no-namespace packages implicitly renders the Apex code as @NamespaceAccessible.
Note: In Apex, the public access modifier isn’t 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 must use
the global access modifier.
For more information on namespace-based visibility, see Namespace-Based Visibility for Apex Classes in Second-Generation Packages.
global
This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same
application. This access modifier must be used for any method that must be referenced outside of the application, either in SOAP
API or by other Apex code. If you declare a method or variable as global, you must also declare the class that contains it as
global.
Note: We recommend using the global access modifier rarely, if at all. Cross-application dependencies are difficult to
maintain.
To use the private, protected, public, or global access modifiers, use the following syntax:
[(none)|private|protected|public|global] declaration
For example:
// private variable s1
private string s1 = '1';
Characteristics
Static methods, variables, and initialization code have these characteristics.
• They’re associated with a class.
• They’re allowed only in outer classes.
• They’re initialized only when a class is loaded.
68
Apex Developer Guide Classes, Objects, and Interfaces
• They aren’t transmitted as part of the view state for a Visualforce page.
Instance methods, member variables, and initialization code have these characteristics.
• They’re associated with a particular object.
• They have no definition modifier.
• They’re created with every object instantiated from the class in which they’re declared.
Local variables have these characteristics.
• They’re associated with the block of code in which they’re declared.
• They must be initialized before they’re used.
The following example shows a local variable whose scope is the duration of the if code block.
Boolean myCondition = true;
if (myCondition) {
integer localVariable = 10;
}
A trigger that uses this class could then selectively fail the first run of the trigger.
trigger T1 on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(p.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
p.firstRun=false;
}
}
}
}
69
Apex Developer Guide Classes, Objects, and Interfaces
A static variable defined in a trigger doesn't retain its value between different trigger contexts within the same transaction, such as
between before insert and after insert invocations. Instead, define the static variables in a class so that the trigger can access these class
member variables and check their static values.
A class static variable can’t be accessed through an instance of that class. If class MyClass has a static variable myStaticVariable,
and myClassInstance is an instance of MyClass, myClassInstance.myStaticVariable isn’t a legal expression.
The same is true for instance methods. If myStaticMethod() is a static method, myClassInstance.myStaticMethod()
isn’t legal. Instead, refer to those static identifiers using the class: MyClass.myStaticVariable and
MyClass.myStaticMethod().
Local variable names are evaluated before class names. If a local variable has the same name as a class, the local variable hides methods
and variables on the class of the same name. For example, this method works if you comment out the String line. But if the String
line is included the method doesn’t compile, because Salesforce reports that the method doesn’t exist or has an incorrect signature.
public static void method() {
String Database = '';
Database.insert(new Account());
}
An inner class behaves like a static Java inner class, but doesn’t require the static keyword. An inner class can have instance member
variables like an outer class, but there’s no implicit pointer to an instance of the outer class (using the this keyword).
Note: In API version 20.0 and earlier, if a Bulk API request causes a trigger to fire, each chunk of 200 records for the trigger to
process is split into chunks of 100 records. In Salesforce API version 21.0 and later, no further splits of API chunks occur. If a Bulk
API request causes a trigger to fire multiple times for chunks of 200 records, governor limits are reset between these trigger
invocations for the same HTTP request. Static variables aren’t reset within the multiple trigger invocations for the same Bulk API
request.
Point(Double x, Double y) {
this.x = x;
this.y = y;
}
Double getXCoordinate() {
return x;
}
Double getYCoordinate() {
return y;
}
}
70
Apex Developer Guide Classes, Objects, and Interfaces
// 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 each time an object is instantiated from that class. These code blocks run before
the constructor.
If you don’t want to write your own constructor for a class, you can use an instance initialization code block to initialize instance variables.
In simple situations, use an ordinary initializer. Reserve initialization code for complex situations, such as initializing a static map. A static
initialization block runs only one time, regardless of how many times you access the class that contains it.
Static initialization code is a block of code preceded with the keyword static.
static {
//code body
Similar to other static code, a static initialization code block is only initialized one time on the first use of the class.
A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body. The code
blocks are executed in the order in which they appear in the file, just as they are in Java.
You can use static initialization code to initialize static final variables and to declare information that’s static, such as a map of values. For
example:
public class MyClass {
class RGB {
Integer red;
Integer green;
Integer blue;
71
Apex Developer Guide Classes, Objects, and Interfaces
}
}
static {
colorMap.put('red', new RGB(255, 0, 0));
colorMap.put('cyan', new RGB(0, 255, 255));
colorMap.put('magenta', new RGB(255, 0, 255));
}
}
Apex Properties
An Apex property is similar to a variable; however, you can do additional things in your code to a property value before it’s accessed or
returned. Properties can be used to validate data before a change is made, to prompt an action when data is changed (such as altering
the value of other member variables), or to 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.
If a property has only a get accessor, it’s considered read-only. If a property has only a set accessor, it’s considered write-only. A property
with both accessors is considered read-write.
To declare a property, use the following syntax in the body of a class:
Public class BasicClass {
// Property declaration
access_modifier return_type property_name {
get {
//Get accessor code block
}
set {
//Set accessor code block
}
}
}
Where:
• access_modifier is the access modifier for the property. The access modifiers that can be applied to properties include:
public, private, global, and protected. In addition, these definition modifiers can be applied: static and
transient. For more information on access modifiers, see Access Modifiers on page 67.
• return_type is the type of the property, such as Integer, Double, sObject, and so on. For more information, see Data Types on
page 24.
• property_name is the name of the property
72
Apex Developer Guide Classes, Objects, and Interfaces
For example, the following class defines a property named prop. The property is public. The property returns an integer data type.
public class BasicProperty {
public integer prop {
get { return prop; }
set { prop = value; }
}
}
The following code segment calls the BasicProperty class, exercising the get and set accessors:
BasicProperty bp = new BasicProperty();
bp.prop = 5; // Calls set accessor
System.assertEquals(5, bp.prop); // Calls get accessor
73
Apex Developer Guide Classes, Objects, and Interfaces
The following code segment calls the static and instance properties:
StaticProperty sp = new StaticProperty();
// The following produces a system error: a static variable cannot be
// accessed through an object instance
// sp.MyGoodStaticProp = 5;
Extending a Class
You can extend a class to provide more specialized behavior.
A class that extends another class inherits all the methods and properties of the extended class. In addition, the extending class can
override the existing virtual methods by using the override keyword in the method definition. Overriding a virtual method allows you
74
Apex Developer Guide Classes, Objects, and Interfaces
to provide a different implementation for an existing method. This means that the behavior of a particular method is different based on
the object you’re calling it on. This is referred to as polymorphism.
A class extends another class using the extends keyword in the class definition. A class can only extend one other class, but it can
implement more than one interface.
This example shows how the YellowMarker class extends the Marker class. To run the inheritance examples in this section, first
create the Marker class.
public virtual class Marker {
public virtual void write() {
System.debug('Writing some text.');
}
Then create the YellowMarker class, which extends the Marker class.
// Extension for the Marker class
public class YellowMarker extends Marker {
public override void write() {
System.debug('Writing some text using the yellow marker.');
}
}
This code segment shows polymorphism. The example declares two objects of the same type (Marker). Even though both objects
are markers, the second object is assigned to an instance of the YellowMarker class. Hence, calling the write method on it yields
a different result than calling this method on the first object, because this method has been overridden. However, you can call the
discount method on the second object even though this method isn't part of the YellowMarker class definition. But it’s part
of the extended class, and hence, is available to the extending class, YellowMarker. Run this snippet in the Execute Anonymous
window of the Developer Console.
Marker obj1, obj2;
obj1 = new Marker();
// This outputs 'Writing some text.'
obj1.write();
The extending class can have more method definitions that aren't common with the original extended class. In this example, the
RedMarker class extends the Marker class and has one extra method, computePrice, that isn't available for the Marker
class. To call the extra methods, the object type must be the extending class.
Before running the next snippet, create the RedMarker class, which requires the Marker class in your org.
// Extension for the Marker class
public class RedMarker extends Marker {
public override void write() {
System.debug('Writing some text in red.');
75
Apex Developer Guide Classes, Objects, and Interfaces
This snippet shows how to call the additional method on the RedMarker class. Run this snippet in the Execute Anonymous window
of the Developer Console.
RedMarker obj = new RedMarker();
// Call method specific to RedMarker only
Double price = obj.computePrice();
Extensions also apply to interfaces—an interface can extend another interface. As with classes, when an interface extends another
interface, all the methods and properties of the extended interface are available to the extending interface.
76
Apex Developer Guide Classes, Objects, and Interfaces
m = 'a';
}
// Inner interface
public virtual interface MyInterface {
// Interface extension
interface MySecondInterface extends MyInterface {
Integer method2(Integer i);
}
77
Apex Developer Guide Classes, Objects, and Interfaces
// 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 {
78
Apex Developer Guide Classes, Objects, and Interfaces
// 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;
79
Apex Developer Guide Classes, Objects, and Interfaces
// o.getInt();
Interfaces
An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of
each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the
interface.
Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the declaration
for that method. This way you can have different implementations of a method based on your specific application.
Defining an interface is similar to defining a new class. For example, a company can have two types of purchase orders, ones that come
from customers, and others that come from their employees. Both are a type of purchase order. Suppose you needed a method to
provide a discount. The amount of the discount can depend on the type of purchase order.
You can model the general concept of a purchase order as an interface and have specific implementations for customers and employees.
In the following example the focus is only on the discount aspect of a purchase order.
Here’s the definition of the PurchaseOrder interface.
// An interface that defines what a purchase order looks like in general
public interface PurchaseOrder {
// All other functionality excluded
Double discount();
}
This class implements the PurchaseOrder interface for customer purchase orders.
// One implementation of the interface for customers
public class CustomerPurchaseOrder implements PurchaseOrder {
public Double discount() {
return .05; // Flat 5% discount
}
}
This class implements the PurchaseOrder interface for employee purchase orders.
// Another implementation of the interface for employees
public class EmployeePurchaseOrder implements PurchaseOrder {
public Double discount() {
return .10; // It’s worth it being an employee! 10% discount
}
}
80
Apex Developer Guide Classes, Objects, and Interfaces
• The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access modifiers
and contain just their signature.
• The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount
method. Any class that implements an interface must define all the methods contained in the interface.
When you define a new interface, you’re defining a new data type. You can use an interface name in any place you can use another data
type name. Any object assigned to a variable of type interface must be an instance of a class that implements the interface, or a
sub-interface data type.
See also Classes and Casting on page 112.
Note: You can’t add a method to a global interface after the class has been uploaded in a Managed - Released package version.
IN THIS SECTION:
1. Custom Iterators
Custom Iterators
An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for exiting the
loop, and you must provide some means of traversing the collection, that is, an iterator. In this example, count is incremented by 1
every time the loop is executed.
while (count < 11) {
System.debug(count);
count++;
}
Using the Iterator interface you can create a custom set of instructions for traversing a List through a loop. The iterator is useful for
data that exists in sources outside of Salesforce that you would normally define the scope of using a SELECT statement. Iterators can
also be used if you have multiple SELECT statements.
81
Apex Developer Guide Classes, Objects, and Interfaces
while(x.hasNext()){
system.debug(x.next());
}
The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use to
traverse the data structure.
In the following example a custom iterator iterates through a collection:
public class CustomIterator
implements Iterator<Account>{
82
Apex Developer Guide Classes, Objects, and Interfaces
}
}
Keywords
Apex provides the keywords final, instanceof, super, this, transient, with sharing and without sharing.
IN THIS SECTION:
1. Using the final Keyword
2. Using the instanceof Keyword
3. Using the super Keyword
4. Using the this Keyword
5. Using the transient Keyword
6. Using the with sharing, without sharing, and inherited sharing Keywords
Use the with sharing or without sharing keywords on a class to specify whether sharing rules must be enforced. Use
the inherited sharing keyword on a class to run the class in the sharing mode of the class that called it.
SEE ALSO:
Reserved Keywords
83
Apex Developer Guide Classes, Objects, and Interfaces
Note: In Apex saved with API version 32.0 and later, instanceof returns false if the left operand is a null object. For
example, the following sample returns false.
Object o = null;
Boolean result = o instanceof Account;
System.assertEquals(false, result);
In API version 31.0 and earlier, instanceof returns true in this case.
public SuperClass() {
mySalutation = 'Mr.';
84
Apex Developer Guide Classes, Objects, and Interfaces
myFirstName = 'Carl';
myLastName = 'Vonderburg';
}
mySalutation = salutation;
myFirstName = firstName;
myLastName = lastName;
}
You can create the following class that extends Superclass and overrides its printName method:
public class Subclass extends Superclass {
public override void printName() {
super.printName();
System.debug('But you can call me ' + super.getFirstName());
}
}
The expected output when calling Subclass.printName is My name is Mr. Vonderburg. But you can call
me Carl.
You can also use super to call constructors. Add the following constructor to SubClass:
public Subclass() {
super('Madam', 'Brenda', 'Clapentrap');
}
Now, the expected output of Subclass.printName is My name is Madam Clapentrap. But you can call
me Brenda.
85
Apex Developer Guide Classes, Objects, and Interfaces
You can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it appears.
Use this form of the this keyword to access instance variables and methods. For example:
public class myTestThis {
string s;
{
this.s = 'TestString';
}
}
In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable using the
this keyword.
Or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this format, use
the this keyword with parentheses. For example:
public class testThis {
When you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor.
You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes
that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types
of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce
page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many
system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These
objects include the following:
• PageReferences
• XmlStream classes
• Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as
a collection of Savepoints
• Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
86
Apex Developer Guide Classes, Objects, and Interfaces
DateTime t1;
transient DateTime t2;
SEE ALSO:
Apex Reference Guide: JSONParser Class
Using the with sharing, without sharing, and inherited sharing Keywords
Use the with sharing or without sharing keywords on a class to specify whether sharing rules must be enforced. Use the
inherited sharing keyword on a class to run the class in the sharing mode of the class that called it.
With Sharing
Use the with sharing keyword when declaring a class to enforce sharing rules of the current user. Explicitly setting this keyword
ensures that Apex code runs in the current user context. Apex code that is executed with the executeAnonymous call and Connect
in Apex always execute using the sharing rules of the current user. For more information on executeAnonymous, see Anonymous
Blocks on page 239.
Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For example:
public with sharing class sharingClass {
// Code here
87
Apex Developer Guide Classes, Objects, and Interfaces
Without Sharing
Use the without sharing keyword when declaring a class to ensure that the sharing rules for the current user are not enforced.
For example, you can explicitly turn off sharing rule enforcement when a class is called from another class that is declared using with
sharing.
// Code here
Inherited Sharing
Use the inherited sharing keyword when declaring a class to enforce the sharing rules of the class that calls it. Using
inherited sharing is an advanced technique to determine the sharing mode at runtime and design Apex classes that can run
in either with sharing or without sharing mode.
Warning: Because the sharing mode is determined at runtime, you must take extreme care to ensure that your Apex code is
secure to run in both with sharing and without sharing modes.
Using inherited sharing, along with other appropriate security checks, facilitates in passing AppExchange security review and
ensures that your privileged Apex code isn’t used in unexpected or insecure ways. An Apex class with inherited sharing runs
as with sharing when used as:
• An Aura component controller
• A Visualforce controller
• An Apex REST service
• Any other entry point to an Apex transaction such as an asynchronous Apex class.
There’s a distinct difference between an Apex class that is marked with inherited sharing and one with an omitted sharing
declaration. If the class is used as the entry point to an Apex transaction, an omitted sharing declaration runs as without sharing.
However, inherited sharing ensures that the default is to run as with sharing. A class declared as inherited
sharing runs as without sharing only when explicitly called from an already established without sharing context.
Example: This example declares an Apex class with inherited sharing and a Visualforce invocation of that Apex code.
Because of the inherited sharing declaration, only contacts for which the running user has sharing access are displayed.
If the declaration is omitted, contacts that the user has no rights to view are displayed due to the insecure default behavior.
public inherited sharing class InheritedSharingClass {
public List<Contact> getAllTheSecrets() {
return [SELECT Name FROM Contact];
}
}
<apex:page controller="InheritedSharingClass">
<apex:repeat value="{!allTheSecrets}" var="record">
{!record.Name}
</apex:repeat>
</apex:page>
88
Apex Developer Guide Classes, Objects, and Interfaces
Implementation Details
• The sharing setting of the class where a method is defined is applied, not of the class where the method is called from. For example,
if a method is defined in a class declared as with sharing is called by a class declared as without sharing, the method
executes with sharing rules enforced.
• If a class isn’t explicitly declared as either with sharing or without sharing, the current sharing rules remain in effect.
Therefore, the class doesn’t enforce sharing rules except when it acquires sharing rules from another class. For example, if the class
is called by another class that has sharing enforced, then sharing is enforced for the called class.
• Both inner classes and outer classes can be declared as with sharing. Inner classes do not inherit the sharing setting from their
container class. Otherwise, the sharing setting applies to all code contained in the class, including initialization code, constructors,
and methods.
• Classes inherit sharing setting from a parent class when one class extends another.
• Apex triggers can’t have an explicit sharing declaration and run as without sharing.
• Asynchronous Apex classes defined with inherited sharing always run in with sharing mode for asynchronous
operations. Each asynchronous operation is a new entry point and the sharing mode is not serialized.
Best Practices
Apex without an explicit sharing declaration is insecure by default. We strongly recommend that you always specify a sharing declaration
for a class.
Regardless of the sharing mode, object-level access and field-level security are not enforced by Apex. You must enforce object-level
access and field-level security in your SOQL queries or code. For example, with sharing mechanism doesn’t enforce user’s access
to view reports and dashboards. You must explicitly enforce running user’s CRUD (Create, Read, Update, Delete) and field-level security
in your code. See Enforcing Object and Field Permissions.
without sharing Use this mode with caution. Ensure that you don’t inadvertently
expose sensitive data that would normally be hidden by the sharing
model. This sharing mechanism is best used to grant targeted
elevation of sharing privileges to the current user.
For example, use without sharing to allow community
users to read records to which they wouldn’t otherwise have access.
inherited sharing Use this mode for service classes that have to be flexible and
support use cases with different sharing modes while also
defaulting to the more secure with sharing mode.
Annotations
An Apex annotation modifies the way that a method or class is used, similar to annotations in Java. Annotations are defined with an
initial @ symbol, followed by the appropriate keyword.
89
Apex Developer Guide Classes, Objects, and Interfaces
To add an annotation to a method, specify it immediately before the method or class definition. For example:
IN THIS SECTION:
1. AuraEnabled Annotation
2. Deprecated Annotation
3. Future Annotation
4. InvocableMethod Annotation
Use the InvocableMethod annotation to identify methods that can be run as invocable actions.
5. InvocableVariable Annotation
To identify variables used by invocable methods in custom classes, use the InvocableVariable annotation.
90
Apex Developer Guide Classes, Objects, and Interfaces
6. IsTest Annotation
7. JsonAccess Annotation
The @JsonAccess annotation defined at Apex class level controls whether instances of the class can be serialized or deserialized.
If the annotation restricts the JSON or XML serialization and deserialization, a runtime JSONException exception is thrown.
8. NamespaceAccessible Annotation
9. ReadOnly Annotation
10. RemoteAction Annotation
11. SuppressWarnings Annotation
This annotation does nothing in Apex but can be used to provide information to third-party tools.
12. TestSetup Annotation
Methods defined with the @TestSetup annotation are used for creating common test records that are available for all test
methods in the class.
13. TestVisible Annotation
AuraEnabled Annotation
The @AuraEnabled annotation enables client-side and server-side access to an Apex controller method. Providing this annotation
makes your methods available to your Lightning components (both Lightning web components and Aura components). Only methods
with this annotation are exposed.
In API version 44.0 and later, you can improve runtime performance by caching method results on the client by using the annotation
@AuraEnabled(cacheable=true). You can cache method results only for methods that retrieve data but don’t modify it.
Using this annotation eliminates the need to call setStorable() in JavaScript code on every action that calls the Apex method.
In API version 55.0 and later, you can use the annotation @AuraEnabled(cacheable=true scope='global') to enable
Apex methods to be cached in a global cache.
For more information, see Lightning Aura Components Developer Guide and Lightning Web Components Developer Guide.
Deprecated Annotation
Use the Deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be
referenced in subsequent releases of the managed package in which they reside. This annotation is useful when you’re refactoring code
in managed packages as the requirements evolve. New subscribers can’t see the deprecated elements, while the elements continue to
function for existing subscribers and API integrations.
The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums, interfaces,
or variables.
@Deprecated
// This method is deprecated. Use myOptimizedMethod(String a, String b) instead.
global void myMethod(String a) {
91
Apex Developer Guide Classes, Objects, and Interfaces
• Unmanaged packages can’t contain code that uses the deprecated keyword.
• When an Apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be deprecated.
Any global method that uses the deprecated type in its signature, either in an input argument or the method return type, must also
be deprecated. A deprecated item, such as a method or a class, can still be referenced internally by the package developer.
• webservice methods and variables can’t be deprecated.
• You can deprecate an enum but you can’t deprecate individual enum values.
• You can deprecate an interface but you can’t deprecate individual methods in an interface.
• You can deprecate an abstract class but you can’t deprecate individual abstract methods in an abstract class.
• You can’t remove the Deprecated annotation to undeprecate something in Apex after you’ve released a package version where
that item in Apex is deprecated.
For more information about package versions, see What is a Package? on page 703.
Future Annotation
Use the Future annotation to identify methods that are executed asynchronously. When you specify Future, the method executes
when Salesforce has available resources.
For example, you can use the Future annotation when making an asynchronous Web service callout to an external service. Without
the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no additional processing
can occur until the callout is complete (synchronous processing).
Methods with the Future annotation must be static methods, and can only return a void type. The specified parameters must be
primitive data types, arrays of primitive data types, or collections of primitive data types. Methods with the Future annotation can’t
take sObjects or objects as arguments.
To make a method in a class execute asynchronously, define the method with the Future annotation. For example:
global class MyFutureClass {
@Future
static void myMethod(String a, Integer i) {
System.debug('Method called with: ' + a + ' and ' + i);
// Perform long-running code
}
}
To allow callouts in a Future method, specify (callout=true). The default is (callout=false), which prevents a method
from making callouts.
The following snippet shows how to specify that a method executes a callout:
@Future (callout=true)
public static void doCalloutFromFuture() {
//Add code to perform callout
}
92
Apex Developer Guide Classes, Objects, and Interfaces
• You can’t call a method annotated with Future from a method that also has the Future annotation. Nor can you call a trigger
from an annotated method that calls another annotated method.
InvocableMethod Annotation
Use the InvocableMethod annotation to identify methods that can be run as invocable actions.
Note: If a flow invokes Apex, the running user must have the corresponding Apex class security set in their user profile or permission
set.
Invocable methods are called natively from Rest, Apex, Flow, or Einstein bot that interacts with the external API source. Invocable methods
have dynamic input and output values and support describe calls.
This code sample shows an invocable method with primitive data types.
public class AccountQueryAction {
@InvocableMethod(label='Get Account Names' description='Returns the list of account names
corresponding to the specified account IDs.' category='Account')
public static List<String> getAccountNames(List<ID> ids) {
List<Account> accounts = [SELECT Name FROM Account WHERE Id in :ids];
Map<ID, String> idToName = new Map<ID, String>();
for (Account account : accounts) {
idToName.put(account.Id, account.Name);
}
// put each name in the output at the same position as the id in the input
List<String> accountNames = new List<String>();
for (String id : ids) {
accountNames.add(idToName.get(id));
}
return accountNames;
}
}
This code sample shows an invocable method with a specific sObject data type.
public class AccountInsertAction {
@InvocableMethod(label = 'Insert Accounts' description='Inserts the accounts specified
and returns the IDs of the new accounts or null if account is failed to create.' category
= 'Account')
public static List<ID> insertAccounts(List<Account> accounts) {
Database.SaveResult[] results = Database.insert(accounts, false);
List<ID> accountIds = new List<ID>();
return accountIds;
}
}
93
Apex Developer Guide Classes, Objects, and Interfaces
This code sample shows an invocable method with the generic sObject data type.
public with sharing class GetFirstFromCollection {
@InvocableMethod
public static List<Results> execute (List<Requests> requestList) {
List<Results> results = new List<Results>();
for (Requests request : requestList) {
List<SObject> inputCollection = request.inputCollection;
SObject outputMember = inputCollection[0];
//Add Result to the results List at the same position as the request is in the
requests List
results.add(result);
}
return results;
}
This code sample shows an invocable method with a custom icon from an SVG file.
global class CustomSvgIcon {
@InvocableMethod(label='myIcon' iconName='resource:myPackageNamespace__google:top')
global static List<Integer> myMethod(List<Integer> request) {
List<Integer> results = new List<Integer>();
for(Integer reqInt : request) {
results.add(reqInt);
}
return results;
}
}
This code sample shows an invocable method with a custom icon from the Salesforce Lightning Design System (SLDS).
public class CustomSldsIcon {
@InvocableMethod(iconName='slds:standard:choice')
public static void run() {}
94
Apex Developer Guide Classes, Objects, and Interfaces
To handle exceptions within an invocable method, wrap the results in an Apex object that reports failures. The execution of the invocable
method must run and return the same number of results as inputs received even if errors occur.
For example, this code sample adjusts positive values by taking their square root and multiplying by pi, setting a success flag to true.
For negative values, it sets the success flag to false.
global class AdjustPositiveValuesAction {
@InvocableMethod(label='Adjust Positive Values' description='Returns the list of adjusted
values. If a number is negative, a failure is reported for that value.')
try {
// Adjust the value, scale by pi.
// Note: If the value is negative, this operation throws an exception.
result.adjustedValue = Math.sqrt(value) * Math.PI;
result.adjustmentSucceeded = true;
}
catch (Exception e) {
// If a negative value caused an exception, mark the adjustment as failed, and keep
processing other values.
result.adjustmentSucceeded = false;
}
results.add(result);
}
return results;
}
This test method checks whether the value adjustments were successful and verifies the calculated values for positive inputs.
// Test class for AdjustPositiveValuesAction
@isTest
private class AdjustPositiveValuesActionTest {
private static testMethod void doTest() {
// Create a list of test values: 4, -1, 1
List<Double> values = new List<Double>();
values.add(4);
values.add(-1);
95
Apex Developer Guide Classes, Objects, and Interfaces
values.add(1);
Test.startTest();
Test.stopTest();
// Assertions to check if adjustments were successful or not for each input value.
system.assertEquals(true, results[0].adjustmentSucceeded);
system.assertEquals(false, results[1].adjustmentSucceeded);
system.assertEquals(true, results[2].adjustmentSucceeded);
Supported Modifiers
All modifiers are optional.
label
The label for the method, which appears as the action name in Flow Builder. The default is the method name, though we recommend
that you provide a label.
description
The description for the method, which appears as the action description in Flow Builder. The default is Null.
callout
The callout modifier identifies whether the method calls to an external system. If the method calls to an external system, add
callout=true. The default value is false.
capabilityType
The capability that integrates with the method. The valid format is Name://Name, for example:
PromptTemplateType://SalesEmail
category
The category for the method, which appears as the action category in Flow Builder. If no category is provided (by default), actions
appear under Uncategorized.
configurationEditor
The custom property editor that is registered with the method and appears in Flow Builder when an admin configures the action.
If you don’t specify this modifier, Flow Builder uses the standard property editor.
iconName
The name of the icon to use as a custom icon for the action in the Flow Builder canvas. You can specify an SVG file that you uploaded
as a static resource or a Salesforce Lightning Design System standard icon.
96
Apex Developer Guide Classes, Objects, and Interfaces
InvocableMethod Considerations
Implementation Notes
• The invocable method must be static and public or global, and its class must be an outer class.
• Only one method in a class can have the InvocableMethod annotation.
• Other annotations can’t be used with the InvocableMethod annotation.
Inputs and Outputs
There can be at most one input parameter and its data type must be one of the following:
• A list of a primitive data type or a list of lists of a primitive data type – the generic Object type isn’t supported.
• A list of an sObject type or a list of lists of an sObject type.
• A list of the generic sObject type (List<sObject>) or a list of lists of the generic sObject type (List<List<sObject>>).
• A list of a user-defined type, containing variables of the supported types or user-defined Apex types, with the
InvocableVariable annotation. To implement your data type, create a custom global or public Apex class. The class
must contain at least one member variable with the invocable variable annotation.
If the return type isn’t Null, the data type returned by the method must be one of the following:
• A list of a primitive data type or a list of lists of a primitive data type – the generic Object type isn’t supported.
• A list of an sObject type or a list of lists of an sObject type.
• A list of the generic sObject type (List<sObject>) or a list of lists of the generic sObject type (List<List<sObject>>).
• A list of a user-defined type, containing variables of the supported types or user-defined Apex types, with the
InvocableVariable annotation. To implement your data type, create a custom global or public Apex class. The class
must contain at least one member variable with the invocable variable annotation.
Note: For a correct bulkification implementation, the Inputs and Outputs must match on both the size and the order. For
example, the i-th Output entry must correspond to the i-th Input entry. Matching entries are required for data correctness
when your action is in bulkified execution, such as when an apex action is used in a record trigger flow.
Managed Packages
• You can use invocable methods in packages, but after you add an invocable method you can’t remove it from later versions of
the package.
• Public invocable methods can be referred to by flows and processes within the managed package.
• Global invocable methods can be referred to anywhere in the subscriber org. Only global invocable methods appear in Flow
Builder and Process Builder in the subscriber org.
For more information about invocable actions, see the Actions Developer Guide.
SEE ALSO:
InvocableVariable Annotation
Actions Developer Guide: Apex Actions
REST API Developer Guide: Invocable Actions
Salesforce Help: Add a Custom Icon to an Apex-Defined Action
Apex Reference Guide: Action Class
Lightning Web Components Developer Guide: Develop Custom Property Editors for Flow Builder
Prompt Builder: Ground with Apex
Making Callouts to External Systems from Invocable Actions
97
Apex Developer Guide Classes, Objects, and Interfaces
InvocableVariable Annotation
To identify variables used by invocable methods in custom classes, use the InvocableVariable annotation.
The InvocableVariable annotation identifies a class variable used as an input or output parameter for an InvocableMethod
method’s invocable action. If you create your own custom class to use as the input or output to an invocable method, you can annotate
individual class member variables to make them available to the method.
This code sample shows an invocable method with invocable variables.
global class ConvertLeadAction {
@InvocableMethod(label='Convert Leads')
global static List<ConvertLeadActionResult> convertLeads(List<ConvertLeadActionRequest>
requests) {
List<ConvertLeadActionResult> results = new List<ConvertLeadActionResult>();
for (ConvertLeadActionRequest request : requests) {
results.add(convertLead(request));
}
return results;
}
if (request.accountId != null) {
lc.setAccountId(request.accountId);
}
if (request.contactId != null) {
lc.setContactId(request.contactId);
}
if (request.opportunityName != null) {
lc.setOpportunityName(request.opportunityName);
}
if (request.ownerId != null) {
lc.setOwnerId(request.ownerId);
}
98
Apex Developer Guide Classes, Objects, and Interfaces
@InvocableVariable(required=true)
global String convertedStatus;
@InvocableVariable
global ID accountId;
@InvocableVariable
global ID contactId;
@InvocableVariable
global Boolean overWriteLeadSource;
@InvocableVariable
global Boolean createOpportunity;
@InvocableVariable
global String opportunityName;
@InvocableVariable
global ID ownerId;
@InvocableVariable
global Boolean sendEmailToOwner;
}
@InvocableVariable
global ID contactId;
@InvocableVariable
global ID opportunityId;
}
99
Apex Developer Guide Classes, Objects, and Interfaces
This code sample shows an invocable method with invocable variables that have the generic sObject data type.
public with sharing class GetFirstFromCollection {
@InvocableMethod
public static List <Results> execute (List<Requests> requestList) {
List<SObject> inputCollection = requestList[0].inputCollection;
SObject outputMember = inputCollection[0];
Supported Modifiers
All modifiers are optional.
Tip: Default values, labels, and placeholder text appear in Flow Builder for the Action element that corresponds to an invocable
method. These modifiers help admins understand how to use variables in the flow.
defaultValue
The default value for the variable. Valid invocable variable data types are:
• Boolean
• Decimal
• Double
• Integer
• Long
• String
description
The description for the variable. The default is Null.
100
Apex Developer Guide Classes, Objects, and Interfaces
label
The label for the variable. The default is the variable name.
placeholderText
Provides examples or additional guidance about the invocable variable, such as examples of values that can set the invocable variable.
Valid invocable variable data types are:
• Double
• Integer
• String
required
Specifies whether the variable is required. If not specified, the default is false. The value is ignored for output variables.
Note: The defaultValue modifier throws an error when used with required.
Example: The invocable variable annotation supports the modifiers shown in this example.
@InvocableVariable(label='yourLabel'
description='yourDescription' placeholderText='yourPlaceholderText'
required=(true | false))
@InvocableVariable(defaultValue='yourDefaultValue')
global Boolean createOpportunity;
InvocableVariable Considerations
• Other annotations can’t be used with the InvocableVariable annotation.
• Only global and public variables can be invocable variables.
• The invocable variable can’t be any of these:
– A non-member variable such as a static or local variable.
– A property.
– A final variable.
– Protected or private.
• The invocable variable name in Apex must match the name in the flow. The name is case-sensitive.
• For managed packages:
– Public invocable variables can be set in flows and processes within the same managed package.
101
Apex Developer Guide Classes, Objects, and Interfaces
– Global invocable variables can be set anywhere in the subscriber org. Only global invocable variables appear in Flow Builder and
Process Builder in the subscriber org.
SEE ALSO:
Apex Developer Guide: InvocableMethod Annotation
Apex Reference Guide: Action Class
IsTest Annotation
Use the @IsTest annotation to define classes and methods that only contain code used for testing your application. The annotation
can take multiple modifiers within parentheses and separated by blanks.
Note: The @IsTest annotation on methods is equivalent to the testMethod keyword. As best practice, Salesforce
recommends that you use @IsTest rather than testMethod. The testMethod keyword may be versioned out in a future
release.
Classes and methods that are defined as @IsTest can be either private or public. Classes defined as @IsTest must be
top-level classes.
Note: Classes defined with the @IsTest annotation don't count against your organization limit of 6 MB for all Apex code.
Here’s an example of a private test class that contains two test methods.
@IsTest
private class MyTestClass {
@IsTest
static void test2() {
// Implement test code
}
Here’s an example of a public test class that contains utility methods for test data creation:
@IsTest
public class TestUtil {
102
Apex Developer Guide Classes, Objects, and Interfaces
@IsTest(SeeAllData=true) Annotation
For Apex code saved using Salesforce API version 24.0 and later, use the @IsTest(SeeAllData=true) annotation to grant test
classes and individual test methods access to all data in the organization. The access includes pre-existing data that the test didn’t create.
Starting with Apex code saved using Salesforce API version 24.0, test methods don’t have access to pre-existing data in the organization.
However, test code saved against Salesforce API version 23.0 and earlier continues to have access to all data in the organization. See
Isolation of Test Data from Organization Data in Unit Tests on page 669.
Considerations for the @IsTest(SeeAllData=true) Annotation
• If a test class is defined with the @IsTest(SeeAllData=true) annotation, the SeeAllData=true applies to all
test methods that don’t explicitly set the SeeAllData keyword.
• The @IsTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level.
However, if the containing class has been annotated with @IsTest(SeeAllData=true), annotating a method with
@IsTest(SeeAllData=false) is ignored for that method. In this case, that method still has access to all the data in
the organization. Annotating a method with @IsTest(SeeAllData=true) overrides, for that method, an
@IsTest(SeeAllData=false) annotation on the class.
• @IsTest(SeeAllData=true) and @IsTest(IsParallel=true) annotations can’t be used together on the
same Apex method.
This example shows how to define a test class with the @IsTest(SeeAllData=true) annotation. All the test methods in this
class have access to all data in the organization.
// All test methods in this class can access all data.
@IsTest(SeeAllData=true)
public class TestDataAccessClass {
// Like the previous method, this test method can also access all data
// because the containing class is annotated with @IsTest(SeeAllData=true).
103
Apex Developer Guide Classes, Objects, and Interfaces
@IsTest
static void myTestMethod2() {
// Can access all data in the organization.
}
This second example shows how to apply the @IsTest(SeeAllData=true) annotation on a test method. Because the test
method’s class isn’t annotated, you have to annotate the method to enable access to all data for the method. The second test method
doesn’t have this annotation, so it can access only the data it creates. In addition, it can access objects that are used to manage your
organization, such as users.
// This class contains test methods with different data access levels.
@IsTest
private class ClassWithDifferentDataAccess {
@IsTest(OnInstall=true) Annotation
Use the @IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This
annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are part of
a test class that has this annotation, are executed during package installation. Tests annotated to run during package installation must
pass in order for the package installation to succeed. It’s no longer possible to bypass a failing test during package installation. A test
method or a class that doesn't have this annotation, or that is annotated with @IsTest(OnInstall=false) or @IsTest, isn’t
executed during installation.
Tests annotated with IsTest(OnInstall=true) that run during package install and upgrade aren’t counted towards code
coverage. However, code coverage is tracked and counted during a package creation operation. Because Apex code installed from a
managed package is excluded from org level requirements for code coverage, it’s unlikely that you’re affected. But, if you track managed
104
Apex Developer Guide Classes, Objects, and Interfaces
package test coverage, you must rerun these tests outside of the package install or upgrade operation for code coverage statistics to be
updated. Package install isn’t blocked by code coverage requirements.
This example shows how to annotate a test method that is executed during package installation. In this example, test1 is executed
but test2 and test3 isn’t.
public class OnInstallClass {
// Implement logic for the class.
public void method1(){
// Some code
}
}
@IsTest
private class OnInstallClassTest {
// This test method will be executed
// during the installation of the package.
@IsTest(OnInstall=true)
static void test1() {
// Some test code
}
@IsTest
static void test2() {
// Some test code
}
@IsTest
static void test3() {
// Some test code
}
}
@IsTest(IsParallel=true) Annotation
Use the @IsTest(IsParallel=true) annotation to indicate test classes that can run in parallel.
Considerations for the @IsTest(IsParallel=true) annotation
• This annotation forces the test to run in parallel even if the org-wide Disable Parallel Apex Testing option is
set.
• @IsTest(SeeAllData=true) and @IsTest(IsParallel=true) annotations can’t be used together on the
same Apex method.
Restrictions on Apex tests using the @IsTest(IsParallel=true) annotation
• Tests can’t call the Test.getStandardPricebookId()method.
• Tests can’t call the System.schedule() and System.enqueueJob() methods.
• Tests can’t insert a ContentNote SObject.
• Tests can’t create User or GroupMember SObjects.
• Tests can’t use the SObjects that are listed in sObjects That Can't Be Used Together in DML Operations.
105
Apex Developer Guide Classes, Objects, and Interfaces
JsonAccess Annotation
The @JsonAccess annotation defined at Apex class level controls whether instances of the class can be serialized or deserialized. If
the annotation restricts the JSON or XML serialization and deserialization, a runtime JSONException exception is thrown.
The serializable and deserializable parameters of the @JsonAccess annotation enforce the contexts in which Apex
allows serialization and deserialization. You can specify one or both parameters, but you can’t specify the annotation with no parameters.
The valid values for the parameters to indicate whether serialization and deserialization are allowed:
• never: never allowed
• sameNamespace: allowed only for Apex code in the same namespace
• samePackage: allowed only for Apex code in the same package (impacts only second-generation packages)
• always: always allowed for any Apex code
JsonAccess Considerations
• If an Apex class annotated with JsonAccess is extended, the extended class doesn’t inherit this property.
• If the toString method is applied on objects that mustn't be serialized, private data can be exposed. You must override the
toString method on objects whose data must be protected. For example, serializing an object stored as a key in a Map invokes
the toString method. The generated map includes key (string) and value entries, thus exposing all the fields of the object.
This example code shows an Apex class marked with the @JsonAccess annotation.
// SomeSerializableClass is serializable in the same package and deserializable in the
wider namespace
@JsonAccess(serializable='samePackage' deserializable=’sameNamespace’)
public class SomeSerializableClass { }
@JsonAccess(deserializable=’always’)
public class AlwaysDeserializable { }
NamespaceAccessible Annotation
The @NamespaceAccessible makes public Apex in a package available to other packages that use the same namespace. Without
this annotation, Apex classes, methods, interfaces, properties, and abstract classes defined in a 2GP package aren’t accessible to the
other packages with which they share a namespace. Apex that is declared global is always available across all namespaces, and needs
no annotation.
For more information on 2GP managed packages, see Second-Generation Managed Packages in Salesforce DX Developer Guide.
Considerations for Apex Accessibility Across Packages
• You can't use the @NamespaceAccessible annotation for an @AuraEnabled Apex method.
106
Apex Developer Guide Classes, Objects, and Interfaces
• You can add or remove the @NamespaceAccessible annotation at any time, even on managed and released Apex code.
Make sure that you don’t have dependent packages relying on the functionality of the annotation before adding or removing it.
• When adding or removing @NamespaceAccessible Apex from a package, consider the impact to customers with installed
versions of other packages that reference this package’s annotation. Before pushing a package upgrade, ensure that no customer
is running a package version that would fail to fully compile when the upgrade is pushed.
• If a public interface is declared as @NamespaceAccessible, then all interface members inherit the annotation. Individual
interface members can’t be annotated with @NamespaceAccessible.
• If a public or protected variable or method is declared as @NamespaceAccessible, its defining class must be either global or
public with the @NamespaceAccessible annotation.
• If a public or protected inner class is declared as @NamespaceAccessible, its enclosing class must be either global or public
with the @NamespaceAccessible annotation.
This example shows an Apex class marked with the @NamespaceAccessible annotation. The class is accessible to other packages
within the same namespace. The first constructor is also visible within the namespace, but the second constructor isn’t.
// A namespace-visible Apex class
@NamespaceAccessible
public class MyClass {
private Boolean bypassFLS;
ReadOnly Annotation
The @ReadOnly annotation allows you to perform less restrictive queries against the Lightning Platform database by increasing the
limit of the number of returned rows for a request to 1,000,000. All other limits still apply. The annotation blocks the following operations
within the request: DML operations, calls to System.schedule, and enqueued asynchronous Apex jobs.
107
Apex Developer Guide Classes, Objects, and Interfaces
The @ReadOnly annotation is available for REST and SOAP Web services and the Schedulable interface. To use the @ReadOnly
annotation, the top-level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page
calls a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top-level request, not the
Web service.
Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods run with the same relaxed
restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration component like
<apex:pageBlockTable>, you can set the readonly attribute on the <apex:page> tag to true. For more information,
see Working with Large Sets of Data in the Visualforce Developer's Guide.
RemoteAction Annotation
The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is
often referred to as JavaScript remoting.
Note: Methods with the RemoteAction annotation must be static and either global or public.
Add the Apex class as a custom controller or a controller extension to your page.
<apex:page controller="MyController" extension="MyExtension">
Warning: Adding a controller or controller extension grants access to all @RemoteAction methods in that Apex class, even
if those methods aren’t used in the page. Anyone who can view the page can execute all @RemoteAction methods and
provide fake or malicious data to the controller.
Then, add the request as a JavaScript function call. A simple JavaScript remoting invocation takes the following form.
[namespace.]MyController.method(
[parameters...,]
callbackFunction,
[configuration]
);
108
Apex Developer Guide Classes, Objects, and Interfaces
Element Description
callbackFunction The name of the JavaScript function that handles the response from the controller. You can also
declare an anonymous function inline. callbackFunction receives the status of the method
call and the result as parameters.
configuration Configures the handling of the remote call and response. Use this element to change the behavior
of a remoting call, such as whether to escape the Apex method’s response.
In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
@RemoteAction
global static String getItemId(String objectName) { ... }
SuppressWarnings Annotation
This annotation does nothing in Apex but can be used to provide information to third-party tools.
The @SuppressWarnings annotation does nothing in Apex but can be used to provide information to third-party tools.
TestSetup Annotation
Methods defined with the @TestSetup annotation are used for creating common test records that are available for all test methods
in the class.
Syntax
Test setup methods are defined in a test class, take no arguments, and return no value. The following is the syntax of a test setup method.
@TestSetup static void methodName() {
If a test class contains a test setup method, the testing framework executes the test setup method first, before any test method in the
class. Records that are created in a test setup method are available to all test methods in the test class and are rolled back at the end of
test class execution. If a test method changes those records, such as record field updates or record deletions, those changes are rolled
back after each test method finishes execution. The next executing test method gets access to the original unmodified state of those
records.
Note: You can have only one test setup method per test class.
Test setup methods are supported only with the default data isolation mode for a test class. If the test class or a test method has access
to organization data by using the @IsTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class.
Because data isolation for tests is available for API versions 24.0 and later, test setup methods are also available for those versions only.
109
Apex Developer Guide Classes, Objects, and Interfaces
TestVisible Annotation
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test
class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level
for running tests only. This annotation doesn’t change the visibility of members if accessed by non-test classes.
With this annotation, you don’t have to change the access modifiers of your methods and member variables to public if you want to
access them in a test method. For example, if a private member variable isn’t supposed to be exposed to external classes but it must be
accessible by a test method, you can add the TestVisible annotation to the variable definition.
This example shows how to annotate a private class member variable and private method with TestVisible.
public class TestVisibleExample {
// Private member variable
@TestVisible private static Integer recordNumber = 1;
// Private method
@TestVisible private static void updateRecord(String name) {
// Do something
}
}
This test class uses the previous class and contains the test method that accesses the annotated member variable and method.
@IsTest
private class TestVisibleExampleTest {
@IsTest static void test1() {
// Access private variable annotated with TestVisible
Integer i = TestVisibleExample.recordNumber;
System.assertEquals(1, i);
110
Apex Developer Guide Classes, Objects, and Interfaces
RestResource Annotation
The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
Some considerations when using this annotation:
• The URL mapping is relative to https://instance.salesforce.com/services/apexrest/.
• The URL mapping can contain a wildcard (*).
• The URL mapping is case-sensitive. For example, a URL mapping for my_url matches a REST resource containing my_url and
not My_Url.
• To use this annotation, your Apex class must be defined as global.
URL Guidelines
URL path mappings are as follows:
• The path must begin with a forward slash (/).
• The path can be up to 255 characters long.
• A wildcard (*) that appears in a path must be preceded by a forward slash (/). Additionally, unless the wildcard is the last character
in the path, it must be followed by a forward slash (/).
The rules for mapping URLs are:
• An exact match always wins.
• If no exact match is found, find all the patterns with wildcards that match, and then select the longest (by string length) of those.
• If no wildcard match is found, an HTTP response status code 404 is returned.
The URL for a namespaced class contains the namespace. For example, if your class is in namespace abc and the class is mapped to
your_url, then the API URL is modified as follows:
https://instance.salesforce.com/services/apexrest/abc/your_url/. In the case of a URL collision, the
namespaced class is always used.
HttpDelete Annotation
The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This
method is called when an HTTP DELETE request is sent, and deletes the specified resource.
To use this annotation, your Apex method must be defined as global static.
HttpGet Annotation
The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method
is called when an HTTP GET request is sent, and returns the specified resource.
These are some considerations when using this annotation:
• To use this annotation, your Apex method must be defined as global static.
• Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method.
HttpPatch Annotation
The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method
is called when an HTTP PATCH request is sent, and updates the specified resource.
To use this annotation, your Apex method must be defined as global static.
111
Apex Developer Guide Classes, Objects, and Interfaces
HttpPost Annotation
The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method
is called when an HTTP POST request is sent, and creates a new resource.
To use this annotation, your Apex method must be defined as global static.
HttpPut Annotation
The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method
is called when an HTTP PUT request is sent, and creates or updates the specified resource.
To use this annotation, your Apex method must be defined as global static.
In the following code segment, a custom report object is first added to a list of report objects. Then the custom report object is returned
as a report object, which is then cast back into a custom report object.
...
// Create a list of report objects
Report[] Reports = new Report[5];
112
Apex Developer Guide Classes, Objects, and Interfaces
Casting Example
In addition, an interface type can be cast to a sub-interface or a class type that implements that interface.
Tip: To verify if a class is a specific type of class, use the instanceOf keyword. For more information, see Using the
instanceof Keyword on page 84.
IN THIS SECTION:
1. Classes and Collections
2. Collection Casting
SEE ALSO:
Using Custom Types in Map Keys and Sets
113
Apex Developer Guide Classes, Objects, and Interfaces
Collection Casting
Because collections in Apex have a declared type at runtime, Apex allows collection casting.
Collections can be cast in a similar manner that arrays can be cast in Java. For example, a list of CustomerPurchaseOrder objects can be
assigned to a list of PurchaseOrder objects if class CustomerPurchaseOrder is a child of class PurchaseOrder.
public virtual class PurchaseOrder {
}
{
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 objects.
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.
114
Apex Developer Guide Classes, Objects, and Interfaces
– The override keyword must be used explicitly on methods that override base class methods.
• Methods defined in an interface have the same access modifier (public or global) as the interface.
• Exception classes must extend either exception or another user-defined exception.
– Their names must end with the word exception.
– Exception classes have four implicit constructors that are built-in, although you can add others.
• Classes and interfaces can be defined in triggers and anonymous blocks, but only as local.
SEE ALSO:
Exceptions in Apex
Note: To aid backwards-compatibility, classes are stored with the version settings for a specified version of Apex and the API. If
the Apex class references components, such as a custom object, in installed managed packages, the version settings for each
managed package referenced by the class is saved too. Additionally, classes are stored with an isValid flag that is set to true
as long as dependent metadata hasn’t changed since the class was last compiled. If any changes are made to object names or
fields that are used in the class, including superficial changes such as edits to an object or field description, or if changes are made
to a class that calls this class, the isValid flag is set to false. When a trigger or Web service call invokes the class, the code
is recompiled and the user is notified if there are any errors. If there are no errors, the isValid flag is reset to true.
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.
115
Apex Developer Guide Classes, Objects, and Interfaces
• 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 isn’t currently visible, the editor scrolls to that line.
IN THIS SECTION:
1. Naming Conventions
2. Name Shadowing
Naming Conventions
We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and
variable names should be meaningful.
It is not legal to define a class and interface with the same name in the same class. It is also not legal for an inner class to have the same
name as its outer class. However, methods and variables have their own namespaces within the class so these three types of names do
not clash with each other. In particular it is legal for a variable, method, and a class within a class to have the same name.
Name Shadowing
Member variables can be shadowed by local variables—in particular function arguments. This allows methods and constructors of the
standard Java form:
Public Class Shadow {
String s;
Shadow(String s) { this.s = s; } // Same name ok
setS(String s) { this.s = s; } // Same name ok
}
Member variables in one class can shadow member variables with the same name in a parent classes. This can be useful if the two classes
are in different top-level classes and written by different teams. For example, if one has a reference to a class C and wants to gain access
116
Apex Developer Guide Classes, Objects, and Interfaces
to a member variable M in parent class P (with the same name as a member variable in C) the reference should be assigned to a reference
to P first.
Static variables can be shadowed across the class hierarchy—so if P defines a static S, a subclass C can also declare a static S. References
to S inside C refer to that static—in order to reference the one in P, the syntax P.S must be used.
Static class variables cannot be referenced through a class instance. They must be referenced using the raw variable name by itself (inside
that top-level class file) or prefixed with the class name. For example:
public class p1 {
public static final Integer CLASS_INT = 1;
public class c { };
}
p1.c c = new p1.c();
// This is illegal
// Integer i = c.CLASS_INT;
// This is correct
Integer i = p1.CLASS_INT;
Namespace Prefix
The Salesforce application supports the use of namespace prefixes. Namespace prefixes are used in managed AppExchange packages
to differentiate custom object and field names from names used by other organizations.
Important: When creating a namespace, use something that’s useful and informative to users. However, don’t name a namespace
after a person (for example, by using a person's name, nickname, or private information). Once namespaces are assigned, they
cannot be changed.
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
These fully qualified names can be onerous to update in working SOQL or SOSL statements, and Apex once a class is marked as “managed”.
Therefore, Apex supports a default namespace for schema names. When looking at identifiers, the parser assumes that the namespace
of the current object is the namespace of all other objects and fields unless otherwise specified. Therefore, a stored class must 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 the AppExchange.
namespace_prefix.class.method(args)
117
Apex Developer Guide Classes, Objects, and Interfaces
IN THIS SECTION:
1. Using the System Namespace
2. Using the Schema Namespace
The Schema namespace provides classes and methods for working with schema metadata information. We implicitly import
Schema.*, but you must fully qualify your uses of Schema namespace elements when they have naming conflicts with items
in your unmanaged code. If your org contains an Apex class that has the same name as an sObject, add the Schema namespace
prefix to the sObject name in your code.
3. Namespace, Class, and Variable Name Precedence
4. Type Resolution and System Namespace for Types
And:
Similarly, to call a static method on the URL class, you can write either of the following:
System.URL.getCurrentRequestUrl();
Or:
URL.getCurrentRequestUrl();
Note: In addition to the System namespace, there is a built-in System class in the System namespace, which provides
methods like assertEquals and debug. Don’t get confused by the fact that both the namespace and the class have the
same name in this case. The System.debug('debug message'); and System.System.debug('debug
message'); statements are equivalent.
118
Apex Developer Guide Classes, Objects, and Interfaces
When the Database.query statement executes, Apex looks up the query method on the custom Database class first. However,
the query method in this class doesn’t take any parameters and no match is found, hence you get an error. The custom Database
class overrides the built-in Database class in the System namespace. To solve this problem, add the System namespace prefix
to the class name to explicitly instruct the Apex runtime to call the query method on the built-in Database class in the System
namespace:
sObject[] acct = System.Database.query('SELECT Name FROM Account LIMIT 1');
System.debug(acct[0].get('Name'));
SEE ALSO:
Using the Schema Namespace
Schema.DescribeSObjectResult d = Account.sObjectType.getDescribe();
Map<String, Schema.FieldSet> FSMap = d.fieldSets.getMap();
And:
DescribeSObjectResult d = Account.sObjectType.getDescribe();
Map<String, FieldSet> FSMap = d.fieldSets.getMap();
// ...
119
Apex Developer Guide Classes, Objects, and Interfaces
SEE ALSO:
Using the System Namespace
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; }
}
120
Apex Developer Guide Classes, Objects, and Interfaces
c.c1.c2.a.tasks
c.c1.c2.a.contacts.size()
IN THIS SECTION:
1. Setting the Salesforce API Version for Classes and Triggers
2. Setting Package Versions for Apex Classes and Triggers
121
Apex Developer Guide Classes, Objects, and Interfaces
2. Select the Version of the Salesforce API. This version is also the version of Apex associated with the class or trigger.
3. Click Save.
If you pass an object as a parameter in a method call from one Apex class, C1, to another class, C2, and C2 has different fields exposed
due to the Salesforce API version setting, the fields in the objects are controlled by the version settings of C2.
In this example, the Categories field is set to null after calling the insertIdea method in class C2 from a method in the test
class C1, because the Categories field isn’t available in version 13.0 of the API.
The first class is saved using Salesforce API version 13.0:
// This class is saved using Salesforce API version 13.0
// Version 13.0 does not include the Idea.categories field
global class C2
{
global Idea insertIdea(Idea a) {
insert a; // category field set to null on insert
return insertedIdea;
}
}
C2 c2 = new C2();
Idea returnedIdea = c2.insertIdea(i);
// retrieve the new idea
Idea ideaMoreFields = [SELECT title, categories FROM Idea
WHERE Id = :returnedIdea.Id];
122
Apex Developer Guide Classes, Objects, and Interfaces
SEE ALSO:
Apex Reference Guide: Collator Class
Apex Reference Guide: Comparable Interface
Apex Reference Guide: Comparator Interface
Warning: If the object in your map keys or set elements changes after being added to the collection, it won’t be found anymore
because of changed field values.
When using a custom type (your Apex class) for the map key or set elements, provide equals and hashCode methods in your
class. Apex uses these two methods to determine equality and uniqueness of keys for your objects.
123
Apex Developer Guide Classes, Objects, and Interfaces
Keep in mind the following when implementing the equals method. Assuming x, y, and z are non-null instances of your class,
the equals method must be:
– Reflexive: x.equals(x)
– Symmetric: x.equals(y) should return true if and only if y.equals(x) returns true
– Transitive: if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
– Consistent: multiple invocations of x.equals(y) consistently return true or consistently return false
– For any non-null reference value x, x.equals(null) should return false
The equals method in Apex is based on the equals method in Java.
Another benefit of providing the equals method in your class is that it simplifies comparing your objects. You will be able to use the
== operator to compare objects, or the equals method. For example:
if (obj1.equals(obj2)) {
// Do something
}
Sample
This sample shows how to implement the equals and hashCode methods. The class that provides those methods is listed first. It
also contains a constructor that takes two Integers. The second example is a code snippet that creates three objects of the class, two of
which have the same values. Next, map entries are added using the pair objects as keys. The sample verifies that the map has only two
entries since the entry that was added last has the same key as the first entry, and hence, overwrote it. The sample then uses the ==
operator, which works as expected because the class implements equals. Also, some additional map operations are performed, like
124
Apex Developer Guide Classes, Objects, and Interfaces
checking whether the map contains certain keys, and writing all keys and values to the debug log. Finally, the sample creates a set and
adds the same objects to it. It verifies that the set size is two, since only two objects out of the three are unique.
public class PairNumbers {
Integer x,y;
for(PairNumbers pn : m.keySet()) {
System.debug('Key: ' + pn);
}
125
Apex Developer Guide Working with Data in Apex
// Create a set
Set<PairNumbers> s1 = new Set<PairNumbers>();
s1.add(p1);
s1.add(p2);
s1.add(p3);
IN THIS SECTION:
Working with sObjects
In this developer guide, the term sObject refers to any object that can be stored in the Lightning platform database.
Data Manipulation Language
Apex enables you to insert, update, delete or restore data in the database. DML operations allow you to modify records one at a time
or in batches.
SOQL and SOSL Queries
You can evaluate Salesforce Object Query Language (SOQL) or Salesforce Object Search Language (SOSL) statements on-the-fly in
Apex by surrounding the statement in square brackets.
SOQL For Loops
SOQL for loops iterate over all of the sObject records returned by a SOQL query.
sObject Collections
You can manage sObjects in lists, sets, and maps.
Dynamic Apex
Apex Security and Sharing
When you use Apex, the security of your code is critical. You'll need to add user permissions for Apex classes and enforce sharing
rules. Read on to learn about Apex managed sharing and get some security tips.
Custom Settings
Custom settings are similar to custom objects. Application developers can create custom sets of data 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. Formula fields, validation rules, flows, Apex, and SOAP API can then use this
data.
126
Apex Developer Guide Working with Data in Apex
IN THIS SECTION:
sObject Types
An sObject variable represents a row of data and can only be declared in Apex using SOAP API name of the object.
Accessing SObject Fields
Validating sObjects and Fields
sObject Types
An sObject variable represents a row of data and can only be declared in Apex using SOAP API name of the object.
For example:
Account a = new Account();
MyCustomObject__c co = new MyCustomObject__c();
Similar to SOAP API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data type can be used
in code that processes different types of sObjects.
The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example:
sObject s = new Account();
You can also use casting between the generic sObject type and the specific sObject type. For example:
// Cast the generic variable s from the example above
// into a specific account and account variable a
Account a = (Account)s;
// The following generates a runtime error
Contact c = (Contact)s;
Because sObjects work like objects, you can also have the following:
Object obj = s;
// and
a = (Account)obj;
DML operations work on variables declared as the generic sObject data type as well as with regular sObjects.
sObject variables are initialized to null, but can be assigned a valid object reference with the new operator. For example:
Account a = new Account();
Developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sObject. For
example:
Account a = new Account(name = 'Acme', billingcity = 'San Francisco');
For information on accessing existing sObjects from the Lightning Platform database, see “SOQL and SOSL Queries” in the SOQL and
SOSL Reference.
Note: The Lightning 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 28.
127
Apex Developer Guide Working with Data in Apex
Custom Labels
Custom labels aren’t standard sObjects. You can’t 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:
For more information on custom labels, see “Custom Labels” in Salesforce 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 retrieve only the Id field using dot notation.
You can set the Id field for Apex code saved using Salesforce API version 27.0 and later). Alternatively, you can use the generic SObject
put and get methods. See SObject Class.
This example shows how you can access the Id field and operations that aren’t allowed on generic SObjects.
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
// This is allowed
ID id = s.Id;
// The following line results in an error when you try to save
String x = s.Name;
// This line results in an error when you try to save using API version 26.0 or earlier
s.Id = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1].Id;
Note: If your organization has enabled person accounts, you have two different kinds of accounts: business accounts and person
accounts. If your code creates a new account using name, a business account is created. If your code uses LastName, a person
account is created.
If you want to perform operations on an SObject, it is recommended that you first convert it into a specific object. For example:
Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco');
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
ID id = s.ID;
Account convertedAccount = (Account)s;
convertedAccount.name = 'Acme2';
update convertedAccount;
Contact sal = new Contact(FirstName = 'Sal', Account = convertedAccount);
The following example shows how you can use SOSL over a set of records to determine their object types. Once you have converted
the generic SObject record into a Contact, Lead, or Account, you can modify its fields accordingly:
public class convertToCLA {
List<Contact> contacts = new List<Contact>();
List<Lead> leads = new List<Lead>();
128
Apex Developer Guide Working with Data in Apex
if (!records.isEmpty()) {
for (Integer i = 0; i < records.size(); i++) {
SObject record = records[i];
if (record.getSObjectType() == Contact.sObjectType) {
contacts.add((Contact) record);
} else if (record.getSObjectType() == Lead.sObjectType){
leads.add((Lead) record);
} else if (record.getSObjectType() == Account.sObjectType) {
accounts.add((Account) record);
}
}
}
}
}
Note: To erase the current value of a field, set the field to null.
If an Apex method takes an SObject parameter, you can use the System.isSet() method to identify the set fields. If you want to unset any
fields to retain their values, first create an SObject instance. Then apply only the fields you want to be part of the DML operation.
This example code shows how SObject fields are identified as set or unset.
Contact nullFirst = new Contact(LastName='Codey', FirstName=null);
System.assertEquals(true, nullFirst.isSet('FirstName'), 'FirstName is set to a literal
value, so it counts as set');
Contact unsetFirst = new Contact(LastName='Astro');
System.assertEquals(false, unsetFirst.isSet('FirstName'), ‘FirstName is not set’);
An expression with SObject fields of type Boolean evaluates to true only if the SObject field is true. If the field is false or null, the expression
evaluates to false. This example code shows an expression that checks if the IsActive field of a Campaign object is null. Because
this expression always evaluates to false, the code in the if statement is never executed.
Campaign cObj= new Campaign();
...
if (cObj.IsActive == null) {
... // IsActive is evaluated to false and this code block is not executed.
}
129
Apex Developer Guide Working with Data in Apex
IN THIS SECTION:
How DML Works
Adding and Retrieving Data With DML
Apex is tightly integrated with the Lightning Platform persistence layer. Records in the database can be inserted and manipulated
through Apex directly using simple statements. The language in Apex that allows you to add and manage records in the database
is the Data Manipulation Language (DML). In contrast to the SOQL language, which is used for read operations (querying records),
DML is used for write operations.
DML Statements vs. Database Class Methods
Apex offers two ways to perform DML operations: using DML statements or Database class methods. This provides flexibility in how
you perform data operations. DML statements are more straightforward to use and result in exceptions that you can handle in your
code.
DML Operations As Atomic Transactions
DML Operations
Using DML, you can insert new records and commit them to the database. You can also update the field values of existing records.
Exception Handling
More About DML
Here are some things you may want to know about using Data Manipulation Language.
Locking Records
When an sObject record is locked, no other client or user is allowed to make updates either through code or the Salesforce user
interface. The client locking the records can perform logic on the records and make updates with the guarantee that the locked
records won’t be changed by another client during the lock period.
130
Apex Developer Guide Working with Data in Apex
This example is a modified version of the previous example that doesn't hit the governor limit. The DML operation is performed in bulk
by calling update on a list of contacts. This code counts as one DML statement, which is far below the limit of 150.
// List to hold the new contacts to update.
List<Contact> updatedList = new List<Contact>();
List<Contact> conList = [Select Department , Description from Contact];
for(Contact con : conList) {
if (con.Department == 'Finance') {
con.Description = 'New description';
// Add updated contact sObject to the list.
updatedList.add(con);
}
}
Another DML governor limit is the total number of rows that can be processed by DML operations in a single transaction, which is 10,000.
All rows processed by all DML calls in the same transaction count incrementally toward this limit. For example, if you insert 100 contacts
and update 50 contacts in the same transaction, your total DML processed rows are 150. You still have 9,850 rows left (10,000 - 150).
Note: If you execute DML operations within an anonymous block, they execute using the current user’s object and field-level
permissions.
131
Apex Developer Guide Working with Data in Apex
Best Practices
With DML on SObjects, it’s best to construct new instances and only update the fields you wish to modify without querying other fields.
If you query fields other than the fields you wish to update, you may revert queried field values that could have changed between the
query and the DML.
In the previous example, the account referenced by the variable a exists in memory with the required Name field. However, it is not
persisted yet to the Lightning Platform persistence layer. You need to call DML statements to persist sObjects to the database. Here is
an example of creating and persisting this account using the insert statement.
Account a = new Account(Name='Account Example');
insert a;
Also, you can use DML to modify records that have already been inserted. Among the operations you can perform are record updates,
deletions, restoring records from the Recycle Bin, merging records, or converting leads. After querying for records, you get sObject
instances that you can modify and then persist the changes of. This is an example of querying for an existing record that has been
previously persisted, updating a couple of fields on the sObject representation of this record in memory, and then persisting this change
to the database.
// Query existing account.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account Example' LIMIT 1];
// Write the old values the debug log before updating them.
System.debug('Account Name before update: ' + a.Name); // Name is Account Example
System.debug('Account Industry before update: ' + a.Industry);// Industry is not set
// Get a new copy of the account from the database with the two fields.
Account a = [SELECT Name,Industry
FROM Account
WHERE Name='Account of the Day' LIMIT 1];
132
Apex Developer Guide Working with Data in Apex
// DML statement
insert acctList;
This is an equivalent example to the previous one but it uses a method of the Database class instead of the DML verb.
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));
// DML statement
Database.SaveResult[] srList = Database.insert(acctList, false);
One difference between the two options is that by using the Database class method, you can specify whether or not to allow for partial
record processing if errors are encountered. You can do so by passing an additional second Boolean parameter. If you specify false
for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead of exceptions, a result object
array (or one result object if only one sObject was passed in) is returned containing the status of each operation and any errors encountered.
By default, this optional parameter is true, which means that if at least one sObject can’t be processed, all remaining sObjects won’t
and an exception will be thrown for the record that causes a failure.
The following helps you decide when you want to use DML statements or Database class methods.
133
Apex Developer Guide Working with Data in Apex
• Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception that immediately
interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions are handled in most
database procedural languages.
• Use Database class methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML
operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this
form, you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge
success or failure. Note that Database methods also include a syntax that supports thrown exceptions, similar to DML statements.
Note: Most operations overlap between the two, except for a few.
• The convertLead operation is only available as a Database class method, not as a DML statement.
• The Database class also provides methods not available as DML statements, such as methods transaction control and rollback,
emptying the Recycle Bin, and methods related to SOQL queries.
SEE ALSO:
Apex Reference Guide: Database Class Methods
DML Operations
Using DML, you can insert new records and commit them to the database. You can also update the field values of existing records.
IN THIS SECTION:
Inserting and Updating Records
Using DML, you can insert new records and commit them to the database. Similarly, you can update the field values of existing
records.
Upserting Records
Merging Records
Deleting Records
Restoring Deleted Records
Converting Leads
134
Apex Developer Guide Working with Data in Apex
Important: Where possible, we changed noninclusive terms to align with our company value of Equality. We maintained certain
terms to avoid any effect on customer implementations.
This example inserts three account records and updates an existing account record. First, three Account sObjects are created and added
to a list. An insert statement bulk inserts the list of accounts as an argument. Then, the second account record is updated, the billing city
is updated, and the update statement is called to persist the change in the database.
Account[] accts = new List<Account>();
for(Integer i=0;i<3;i++) {
Account a = new Account(Name='Acme' + i,
BillingCity='San Francisco');
accts.add(a);
}
Account accountToUpdate;
try {
insert accts;
135
Apex Developer Guide Working with Data in Apex
FirstName='Joe',
LastName='Smith',
Phone='415.555.1212',
AccountId=acctID);
insert con;
} catch(DmlException e) {
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
IN THIS SECTION:
Relating Records by Using an External ID
Add related records by using a custom external ID field on the parent record. Associating records through the external ID field is an
alternative to using the record ID. You can add a related record to another record only if a relationship (such as master-detail or
lookup) has been defined for the objects involved.
Creating Parent and Child Records in a Single Statement Using Foreign Keys
136
Apex Developer Guide Working with Data in Apex
Important: Where possible, we changed noninclusive terms to align with our company value of Equality. We maintained certain
terms to avoid any effect on customer implementations.
This example relates a new opportunity to an existing account. The Account sObject has a custom field marked as External ID. An
opportunity record is associated to the account record through the custom External ID field. The example assumes that:
• The Account sObject has an external ID field of type text and named MyExtID
• An account record exists where MyExtID__c = ‘SAP111111’
Before the new opportunity is inserted, the account record is added to this opportunity as an sObject through the
Opportunity.Account relationship field.
The previous example performs an insert operation, but you can also relate sObjects through external ID fields when performing updates
or upserts. If the parent record doesn’t exist, you can create it with a separate DML statement or by using the same DML statement as
shown in Creating Parent and Child Records in a Single Statement Using Foreign Keys.
Creating Parent and Child Records in a Single Statement Using Foreign Keys
You can use external ID fields as foreign keys to create parent and child records of different sObject types in a single step instead of
creating the parent record first, querying its ID, and then creating the child record. To do this:
• Create the child sObject and populate its required fields, and optionally other fields.
• Create the parent reference sObject used only for setting the parent foreign key reference on the child sObject. This sObject has only
the external ID field defined and no other fields set.
• Set the foreign key field of the child sObject to the parent reference sObject you just created.
• Create another parent sObject to be passed to the insert statement. This sObject must have the required fields (and optionally
other fields) set in addition to the external ID field.
• Call insert by passing it an array of sObjects to create. The parent sObject must precede the child sObject in the array, that is,
the array index of the parent must be lower than the child’s index.
You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different sObject
types. For more information, see Creating Records for Different Object Types in the SOAP API Developer Guide.
The following example shows how to create an opportunity with a parent account using the same insert statement. The example
creates an Opportunity sObject and populates some of its fields, then creates two Account objects. The first account is only for the foreign
key relationship, and the second is for the account creation and has the account fields set. Both accounts have the external ID field,
137
Apex Developer Guide Working with Data in Apex
MyExtID__c, set. Next, the sample calls Database.insert by passing it an array of sObjects. The first element in the array is
the parent sObject and the second is the opportunity sObject. The Database.insert statement creates the opportunity with its
parent account in a single step. Finally, the sample checks the results and writes the IDs of the created records to the debug log, or the
first error if record creation fails. This sample requires an external ID text field on Account called MyExtID.
public class ParentChildSample {
public static void InsertParentChild() {
Date dt = Date.today();
dt = dt.addDays(7);
Opportunity newOpportunity = new Opportunity(
Name='OpportunityWithAccountInsert',
StageName='Prospecting',
CloseDate=dt);
// Check results.
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
System.debug('Successfully created ID: '
+ results[i].getId());
} else {
System.debug('Error: could not create sobject '
+ 'for array element ' + i + '.');
System.debug(' The error reported was: '
+ results[i].getErrors()[0].getMessage() + '\n');
}
}
}
}
Upserting Records
Using the upsert operation, you can either insert or update an existing record in one call. To determine whether a record already
exists, the upsert statement or Database method uses the record’s ID as the key to match records, a custom external ID field, or a
standard field with the idLookup attribute set to true.
• If the key isn’t matched, then a new object record is created.
138
Apex Developer Guide Working with Data in Apex
• If the key is matched once, then the existing object record is updated.
• If the key is matched multiple times, then an error is generated and the object record is not inserted or updated.
Note: Custom field matching is case-insensitive only if the custom field has the Unique and Treat "ABC" and "abc" as duplicate
values (case insensitive) attributes selected as part of the field definition. If this is the case, “ABC123” is matched with “abc123.”
For more information, see Create Custom Fields.
Examples
The following example updates the city name for all existing accounts in the city formerly known as Bombay, and also inserts a new
account in San Francisco:
Account[] acctsList = [SELECT Id, Name, BillingCity
FROM Account WHERE BillingCity = 'Bombay'];
for (Account a : acctsList) {
a.BillingCity = 'Mumbai';
}
Account newAcct = new Account(Name = 'Acme', BillingCity = 'San Francisco');
acctsList.add(newAcct);
try {
upsert acctsList;
} catch (DmlException e) {
// Process exception here
}
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.
This next example uses the Database.upsert method to upsert a collection of leads that are passed in. This example allows for
partial processing of records, that is, in case some records fail processing, the remaining records are still inserted or updated. It iterates
through the results and adds a task to each record that was processed successfully. The task sObjects are saved in a list, which is then
bulk inserted. This example is followed by a test class that contains a test method for testing the example.
/* This class demonstrates and tests the use of the
* partial processing DML operations */
/* 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())
139
Apex Developer Guide Working with Data in Apex
return uResults;
}
}
@isTest
private class DmlSamplesTest {
public static testMethod void testUpsertLeads() {
/* We only need to test the insert side of upsert */
List<Lead> leads = new List<Lead>();
/* 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());
}
}
}
Use of upsert with an external ID can reduce the number of DML statements in your code, and help you to avoid hitting governor
limits (see Execution Governors and Limits).
This 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. Before running the sample, create a custom text field on the Asset object named
Line_Item_Id__c and mark it as an external ID. For information on custom fields, see Salesforce Help.
140
Apex Developer Guide Working with Data in Apex
Note: External ID fields used in upsert calls must be unique or the user must have the View All Data permission.
FROM OpportunityLineItems)
FROM Opportunity
WHERE HasOpportunityLineItem = true
LIMIT 1];
//This code populates the line item Id, AccountId, and Product2Id for each asset
Asset asset = new Asset(Name = lineItem.PricebookEntry.Name,
Line_Item_ID__c = lineItem.Id,
AccountId = opp.AccountId,
Product2Id = lineItem.PricebookEntry.Product2Id);
assets.add(asset);
}
try {
upsert assets Line_Item_ID__c; // This line upserts the assets list with
// the Line_Item_Id__c field specified as the
// Asset field that should be used for matching
// the record that should be upserted.
} catch (DmlException e) {
System.debug(e.getMessage());
}
}
Merging Records
When you have duplicate lead, contact, case, or account records in the database, cleaning up your data and consolidating the records
might be a good idea. You can merge up to three records of the same sObject type. The merge operation merges up to three records
into one of the records, deletes the others, and reparents any related records.
Example
The following shows how to merge an existing Account record into a master account. The account to merge has a related contact, which
is moved to the master account record after the merge operation. Also, after merging, the merge record is deleted and only one record
remains in the database. This examples starts by creating a list of two accounts and inserts the list. Then it executes queries to get the
new account records from the database, and adds a contact to the account to be merged. Next, it merges the two accounts. Finally, it
verifies that the contact has been moved to the master account and the second account has been deleted.
// Insert new accounts
List<Account> ls = new List<Account>{
new Account(name='Acme Inc.'),
new Account(name='Acme')
141
Apex Developer Guide Working with Data in Apex
};
insert ls;
try {
merge masterAcct mergeAcct;
} catch (DmlException e) {
// Process exception
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
This second example is similar to the previous except that it uses the Database.merge method (instead of the merge statement).
The last argument of Database.merge is set to false to have any errors encountered in this operation returned in the merge
result instead of getting exceptions. The example merges two accounts into the master account and retrieves the returned results. The
example creates a master account and two duplicates, one of which has a child contact. It verifies that after the merge the contact is
moved to the master account.
// Create master account
Account master = new Account(Name='Account1');
insert master;
142
Apex Developer Guide Working with Data in Apex
// Get the account contact relation ID, which is created when a contact is created on
"Account1, Inc."
AccountContactRelation resultAcrel = [SELECT Id FROM AccountContactRelation WHERE
ContactId=:c.Id LIMIT 1];
// Make sure there are two IDs (contact ID and account contact relation ID); the order
isn't defined
System.assertEquals(2, res.getUpdatedRelatedIds().size() );
boolean flag1 = false;
boolean flag2 = false;
// Because the order of the IDs isn't defined, the ID can be at index 0 or 1 of the
array
if (resultAcrel.id == res.getUpdatedRelatedIds()[0] || resultAcrel.id ==
res.getUpdatedRelatedIds()[1] )
flag1 = true;
System.assertEquals(flag1, true);
System.assertEquals(flag2, true);
}
else {
for(Database.Error err : res.getErrors()) {
// Write each error to the debug output
System.debug(err.getMessage());
}
}
}
143
Apex Developer Guide Working with Data in Apex
Merge Considerations
When merging sObject records, consider the following rules and guidelines:
• Only leads, contacts, cases, and accounts can be merged. See sObjects That Don’t Support DML Operations on page 158.
• You can pass a master record and up to two additional sObject records to a single merge method.
• Using the Apex merge operation, field values on the master record always supersede the corresponding field values on the records
to be merged. To preserve a merged record field value, simply set this field value on the master sObject before performing the merge.
• External ID fields can’t be used with merge.
For more information on merging leads, contacts and accounts, see the Salesforce online help.
Deleting Records
After you persist records in the database, you can delete those records using the delete operation. Deleted records aren’t deleted
permanently from Salesforce, but they are placed in the Recycle Bin for 15 days from where they can be restored. Restoring deleted
records is covered in a later section.
Example
The following example deletes all accounts that are named 'DotCom':
Account[] doomedAccts = [SELECT Id, Name FROM Account
WHERE Name = 'DotCom'];
try {
delete doomedAccts;
} catch (DmlException e) {
// Process exception here
}
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.
144
Apex Developer Guide Working with Data in Apex
• Relationship group members on accounts and relationship groups, with some exceptions
• Tags
• An article's categories, publication state, and assignments
Note: Salesforce only restores lookup relationships that have not been replaced. For example, if an asset is related to a different
product prior to the original product record being undeleted, that asset-product relationship is not restored.
Example
The following example undeletes an account named 'Universal Containers'. The ALL ROWS keyword queries all rows for both top
level and aggregate relationships, including deleted records and archived activities.
Account a = new Account(Name='Universal Containers');
insert(a);
insert(new Contact(LastName='Carter',AccountId=a.Id));
delete a;
Account[] savedAccts = [SELECT Id, Name FROM Account WHERE Name = 'Universal Containers'
ALL ROWS];
try {
undelete savedAccts;
} catch (DmlException e) {
// Process exception here
}
Note: For more information on processing DmlExceptions, see Bulk DML Exception Handling.
Undelete Considerations
Note the following when using the undelete statement.
• You can undelete records that were deleted as the result of a merge. However, the merge reparents the child objects, and that
reparenting can’t be undone.
• To identify deleted records, including records deleted as a result of a merge, use the ALL ROWS parameters with a SOQL query.
• See Referential Integrity When Deleting and Restoring Records.
SEE ALSO:
Querying All Records with a SOQL Statement
Converting Leads
The convertLead DML operation converts a lead into an account and contact, as well as (optionally) an opportunity. convertLead
is available only as a method on the Database class; it is not available as a DML statement.
Converting leads involves the following basic steps:
145
Apex Developer Guide Working with Data in Apex
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 uses the query (SELECT ... FROM LeadStatus WHERE IsConverted=true) to obtain the leads
with 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 can’t be
owned by a queue. Even if you are specifying an existing account or contact, you must still specify an owner.
Example
This example shows how to use the Database.convertLead method to convert a lead. It inserts a new lead, creates a
LeadConvert object, sets its status to converted, and then passes it to the Database.convertLead method. Finally, it verifies
that the conversion was successful.
Lead myLead = new Lead(LastName = 'Fry', Company='Fry And Sons');
insert myLead;
LeadStatus convertStatus = [SELECT Id, ApiName FROM LeadStatus WHERE IsConverted=true LIMIT
1];
lc.setConvertedStatus(convertStatus.ApiName);
146
Apex Developer Guide Working with Data in Apex
• Record types: If the organization uses record types, the default record type of the new owner is assigned to records created during
lead conversion. The default record type of the user converting the lead determines the lead source values available during conversion.
If the desired lead source values are not available, add the values to the default record type of the user converting the lead. For more
information about record types, see Salesforce Help.
• Picklist values: The system assigns the default picklist values for the account, contact, and opportunity when mapping any standard
lead picklist fields that are blank. If your organization uses record types, blank values are replaced with the default picklist values of
the new record owner.
• Automatic feed subscriptions: When you convert a lead into a new account, contact, and opportunity, the lead owner is unsubscribed
from the lead record’s Chatter feed. The lead owner, the owner of the generated records, and users that were subscribed to the lead
aren’t automatically subscribed to the generated records, unless they have automatic subscriptions enabled in their Chatter feed
settings. They must have automatic subscriptions enabled to see changes to the account, contact, and opportunity records in their
news feed. To subscribe to records they create, users must enable the Automatically follow records that I
create option in their personal settings. A user can subscribe to a record so that changes to the record display in the news feed
on the user's home page. This is a useful way to stay up-to-date with changes to records in Salesforce.
Exception Handling
DML statements return run-time exceptions if something went wrong in the database during the execution of the DML operations. You
can handle the exceptions in your code by wrapping your DML statements within try-catch blocks. The following example includes the
insert DML statement inside a try-catch block.
IN THIS SECTION:
Database Class Method Result Objects
Returned Database Errors
147
Apex Developer Guide Working with Data in Apex
Example
This example shows how to get the errors returned by a Database.insert operation. It inserts two accounts, one of which doesn’t
have the required Name field, and sets the second parameter to false: Database.insert(accts, false);. This sets the
partial processing option. Next, the example checks if the call had any failures through if (!sr.isSuccess()) and then iterates
through the errors, writing error information to the debug log.
// Create two accounts, one of which is missing a required field
Account[] accts = new List<Account>{
new Account(Name='Account1'),
new Account()};
Database.SaveResult[] srList = Database.insert(accts, false);
IN THIS SECTION:
Setting DML Options
Transaction Control
Read about transaction requests, generating and releasing savepoints, rolling back transactions, and more.
148
Apex Developer Guide Working with Data in Apex
allowFieldTruncation Property
The allowFieldTruncation property specifies the truncation behavior of strings. In Apex saved against API versions previous
to 15.0, if you specify a value for a string and that value is too large, the value is truncated. For API version 15.0 and later, if a value is
specified that is too large, the operation fails and an error message is returned. The allowFieldTruncation property allows you
to specify that the previous behavior, truncation, be used instead of the new behavior in Apex saved against API versions 15.0 and later.
The allowFieldTruncation property takes a Boolean value. If true, the property truncates String values that are too long,
which is the behavior in API versions 14.0 and earlier. For example:
Database.DMLOptions dml = new Database.DMLOptions();
dml.allowFieldTruncation = true;
149
Apex Developer Guide Working with Data in Apex
assignmentRuleHeader Property
The assignmentRuleHeader property specifies the assignment rule to be used when creating a case or lead.
Note: The Database.DMLOptions object supports assignment rules for cases and leads, but not for accounts.
Note: If there are no assignment rules in the organization, in API version 29.0 and earlier, creating a case or lead with
useDefaultRule set to true results in the case or lead being assigned to the predefined default owner. In API version 30.0
and later, the case or lead is unassigned and doesn't get assigned to the default owner.
duplicateRuleHeader Property
The duplicateRuleHeader property determines whether a record that’s identified as a duplicate can be saved. Duplicate rules
are part of the Duplicate Management feature.
Using the duplicateRuleHeader property, you can set these options.
• allowSave: Indicates whether a record that’s identified as a duplicate can be saved.
The following example shows how to save an account record that’s been identified as a duplicate. To learn how to iterate through
duplicate errors, see DuplicateError Class
150
Apex Developer Guide Working with Data in Apex
emailHeader Property
The Salesforce user interface allows you to specify whether or not to send an email when the following events occur:
• Creation of a new case or task
• Conversion of a case email to a contact
• New user email notification
• Lead queue email notification
• Password reset
In Apex saved against API version 15.0 or later, the Database.DMLOptions emailHeader property enables you to specify additional
information regarding the email that gets sent when one of the events occurs because of Apex DML code execution.
Using the emailHeader property, you can set these options.
• triggerAutoResponseEmail: Indicates whether to trigger auto-response rules (true) or not (false), for leads and cases.
This email can be automatically triggered by a number of events, for example when creating a case or resetting a user password. If
this value is set to true, when a case is created, if there is an email address for the contact specified in ContactID, the email is
sent to that address. If not, the email is sent to the address specified in SuppliedEmail.
• triggerOtherEmail: Indicates whether to trigger email outside the organization (true) or not (false). This email can be
automatically triggered by creating, editing, or deleting a contact for a case.
• triggerUserEmail: Indicates whether to trigger email that is sent to users in the organization (true) or not (false). This
email can be automatically triggered by a number of events; resetting a password, creating a new user, or creating or modifying a
task.
Note: Adding comments to a case in Apex doesn’t trigger email to users in the organization even if triggerUserEmail
is set to true.
Even though auto-sent emails can be triggered by actions in the Salesforce user interface, the DMLOptions settings for emailHeader
take effect only for DML operations carried out in Apex code.
In the following example, the triggerAutoResponseEmail option is specified:
Account a = new Account(name='Acme Plumbing');
insert a;
insert c;
dlo.EmailHeader.triggerAutoResponseEmail = true;
database.insert(ca, dlo);
Email sent through Apex because of a group event includes additional behaviors. A group event is an event for which IsGroupEvent
is true. The EventAttendee object tracks the users, leads, or contacts that are invited to a group event. Note the following behaviors for
group event email sent through Apex:
• Sending a group event invitation to a user respects the triggerUserEmail option
151
Apex Developer Guide Working with Data in Apex
• Sending a group event invitation to a lead or contact respects the triggerOtherEmail option
• Email sent when updating or deleting a group event also respects the triggerUserEmail and triggerOtherEmail
options, as appropriate
localeOptions Property
The localeOptions property specifies the language of any labels that are returned by Apex. The value must be a valid user locale
(language and country), such as de_DE or en_GB. The value is a String, 2-5 characters long. The first two characters are always an ISO
language code, for example 'fr' or 'en.' If the value is further qualified by a country, then the string also has an underscore (_) and another
ISO country code, for example 'US' or 'UK.' For example, the string for the United States is 'en_US', and the string for French Canadian is
'fr_CA'.
optAllOrNone Property
The optAllOrNone property specifies whether the operation allows for partial success. If optAllOrNone is set to true, all
changes are rolled back if any record causes errors. The default for this property is false and successfully processed records are
committed while records with errors aren't. This property is available in Apex saved against Salesforce API version 20.0 and later.
Transaction Control
Read about transaction requests, generating and releasing savepoints, rolling back transactions, and more.
All requests are delimited by the trigger, class method, Web Service, Visualforce page, or anonymous block that executes the Apex code.
If the entire request completes successfully, all changes are committed to the database. For example, suppose a Visualforce page called
an Apex controller, which in turn called an additional Apex class. Only when all the Apex code has finished running and the Visualforce
page has finished running, are the changes committed to the database. If the request doesn’t complete successfully, all database changes
are rolled back.
• Database.rollback(Savepoint) and Database.setSavepoint()don’t count against the DML row limit, but
count toward the DML statement limit. This behavior applies to all API versions.
• The ID on an sObject inserted after setting a savepoint isn’t cleared after a rollback. Attempting to insert the sObject using the variable
created before the rollback fails because the sObject variable has an ID. Updating or upserting the sObject using the same variable
152
Apex Developer Guide Working with Data in Apex
also fails because the sObject isn’t in the database and, thus, can’t be updated. To perform further DML operations, create an sObject
variable without setting its ID.
The following is an example using the setSavepoint and rollback Database methods.
Account a = new Account(Name = 'xyz');
insert a;
Assert.isNull([SELECT AccountNumber FROM Account WHERE Id = :a.Id]. AccountNumber);
// Create a savepoint while AccountNumber is null
Savepoint sp = Database.setSavepoint();
// Change the account number
a.AccountNumber = '123';
update a;
Assert.areEqual('123', [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
AccountNumber);
// Rollback to the previous null value
Database.rollback(sp);
Assert.isNull([SELECT AccountNumber FROM Account WHERE Id = :a.Id]. AccountNumber);
In this example, the savepoint isn’t released before making the callout. The CalloutException informs you that you must release
all active savepoints before making the callout.
Savepoint sp = Database.setSavepoint();
try {
makeACallout();
} catch (System.CalloutException ex) {
Assert.isTrue(ex.getMessage().contains('All active Savepoints must be released before
making callouts.'));
}
In this example, DML is pending when the callout is made. The CalloutException informs you that you must roll back the
transaction before the callout is made or the transaction must be committed.
Savepoint sp = Database.setSavepoint();
insert new Account(name='Foo');
153
Apex Developer Guide Working with Data in Apex
Database.releaseSavepoint(sp);
try {
makeACallout();
} catch (System.CalloutException ex) {
Assert.isTrue(ex.getMessage().contains('You have uncommitted work pending. Please commit
or rollback before calling out.'));
}
• GroupMember
Note: With legacy Apex code saved using Salesforce API version 14.0 and earlier, you can insert and update a group member
with other sObjects in the same transaction.
• ObjectPermissions
• ObjectTerritory2AssignmentRule
• ObjectTerritory2AssignmentRuleItem
154
Apex Developer Guide Working with Data in Apex
• PermissionSet
• PermissionSetAssignment
• QueueSObject
• RuleTerritory2Association
• SetupEntityAccess
• Territory
• Territory2
• Territory2Model
• User
You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce API version 14.0 and earlier.
You can insert a user in a transaction with other sObjects in Apex code saved using Salesforce API version 15.0 and later when
UserRoleId is specified as null.
You can update a user in a transaction with other sObjects in Apex code saved using Salesforce API version 14.0 and earlier
You can update a user in a transaction with other sObjects in Apex code saved using Salesforce API version 15.0 and later when the
user isn’t included in a Lightning Sync or Einstein Activity Capture configuration (either active or inactive) and the following fields
aren’t updated:
– UserRoleId
– IsActive
– ForecastEnabled
– IsPortalEnabled
– Username
– ProfileId
• UserPackageLicense
• UserRole
• UserTerritory
• UserTerritory2Association
If you're using a Visualforce page with a custom controller, you can't mix sObject types with any of these special sObjects within a single
request or action. However, you can perform DML operations on these different types of sObjects in subsequent requests. For example,
you can create an account with a save button, and then create a user with a non-null role with a submit button.
You can perform DML operations on more than one type of sObject in a single class using the following process:
1. Create a method that performs a DML operation on one type of sObject.
2. Create a second method that uses the future annotation to manipulate a second sObject type.
This process is demonstrated in the example in the next section.
155
Apex Developer Guide Working with Data in Apex
insert a;
IN THIS SECTION:
Mixed DML Operations in Test Methods
Test methods allow for performing mixed Data Manipulation Language (DML) operations that include both setup sObjects and
other sObjects if the code that performs the DML operations is enclosed within System.runAs method blocks. You can also
perform DML in an asynchronous job that your test method calls. These techniques enable you, for example, to create a user with
a role and other sObjects in the same test.
Note: Because validation for mixed DML operations is skipped during deployment, there can be a difference in the number of
test failures when tests are deployed versus when run in the user interface.
156
Apex Developer Guide Working with Data in Apex
157
Apex Developer Guide Working with Data in Apex
Note: All standard and custom objects can also be accessed through the SOAP API. ProcessInstance is an exception. You can’t
create, update, or delete ProcessInstance in the SOAP API.
158
Apex Developer Guide Working with Data in Apex
Note:
– During the second and third attempts, governor limits are reset to their original state before the first attempt. See Execution
Governors and Limits on page 321.
– Apex triggers are fired for the first save attempt, and if errors are encountered for some records and subsequent attempts
are made to save the subset of successful records, triggers are refired on this subset of records.
159
Apex Developer Guide Working with Data in Apex
The insert and update statements check each batch of records for duplicate ID values. If there are duplicates, the first five are
processed. For the sixth and all additional duplicate IDs, the SaveResult for those entries is marked with an error similar to the following:
Maximum number of duplicate updates in one batch (5 allowed). Attempt to update Id
more than once in this API call: number_of_attempts.
The ID of an updated sObject record cannot be modified in an update statement, but related record IDs can.
Fields With Unique Constraints
For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For example,
inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup records must have
unique names.
System Fields Automatically Set
When inserting new records, system fields such as CreatedDate, CreatedById, and SystemModstamp are automatically
updated. You cannot explicitly specify these values in your Apex. Similarly, when updating records, system fields such as
LastModifiedDate, LastModifiedById, and SystemModstamp are automatically updated.
Maximum Number of Records Processed by DML Statement
You can pass a maximum of 10,000 sObject records to a single insert, update, delete, and undelete method.
Each upsert statement consists of two operations, one for inserting records and one for updating records. Each of these operations
is subject to the runtime limits for insert and update, respectively. For example, if you upsert more than 10,000 records and
all of them are being updated, you receive an error. (See Execution Governors and Limits on page 321)
Upsert and Foreign Keys
You can use foreign keys to upsert sObject records if they have been set as reference fields. For more information, see Field Types
in the Object Reference for Salesforce.
Creating Records for Multiple Object Types
As with the SOAP API, you can create records in Apex for multiple object types, including custom objects, in one DML call with API
version 20.0 and later. For example, you can create a contact and an account in one call. You can create records for up to 10 object
types in one call.
Records are saved in the same order that they’re entered in the sObject input array. If you’re entering new records that have a
parent-child relationship, the parent record must precede the child record in the array. For example, if you’re creating a contact that
references an account that’s also being created in the same call, the account must have a smaller index in the array than the contact
does. The contact references the account by using an External ID field.
You can’t add a record that references another record of the same object type in the same call. For example, the Contact object has
a Reports To field that’s a reference to another contact. You can’t create two contacts in one call if one contact uses the
Reports To field to reference a second contact in the input array. You can create a contact that references another contact that
has been previously created.
Records for multiple object types are broken into multiple chunks by Salesforce. A chunk is a subset of the input array, and each
chunk contains records of one object type. Data is committed on a chunk-by-chunk basis. Any Apex triggers that are related to the
records in a chunk are invoked once per chunk. Consider an sObject input array that contains the following set of records:
account1, account2, contact1, contact2, contact3, case1, account3, account4, contact4
160
Apex Developer Guide Working with Data in Apex
5. contact4
Each call can process up to 10 chunks. If the sObject array contains more than 10 chunks, you must process the records in more than
one call. For additional information about this feature, see Creating Records for Different Object Types in the SOAP API Developer
Guide.
Note: For Apex, the chunking of the input array for an insert or update DML operation has two possible causes: the existence
of multiple object types or the default chunk size of 200. If chunking in the input array occurs because of both of these reasons,
each chunk is counted toward the limit of 10 chunks. If the input array contains only one type of sObject, you won’t hit this
limit. However, if the input array contains at least two sObject types and contains a high number of objects that are chunked
into groups of 200, you might hit this limit. For example, if you have an array that contains 1,001 consecutive leads followed
by 1,001 consecutive contacts, the array will be chunked into 12 groups: Two groups are due to the different sObject types of
Lead and Contact, and the remaining are due to the default chunking size of 200 objects. In this case, the insert or update
operation returns an error because you reached the limit of 10 chunks in hybrid arrays. The workaround is to call the DML
operation for each object type separately.
DML and Knowledge Objects
To execute DML code on knowledge articles (KnowledgeArticleVersion types such as the custom FAQ__kav article type), the running
user must have the Knowledge User feature license. Otherwise, calling a class method that contains DML operations on knowledge
articles results in errors. If the running user isn’t a system administrator and doesn’t have the Knowledge User feature license, calling
any method in the class returns an error even if the called method doesn’t contain DML code for knowledge articles but another
method in the class does. For example, the following class contains two methods, only one of which performs DML on a knowledge
article. A non-administrator non-knowledge user who calls the doNothing method will get the following error: DML operation
UPDATE not allowed on FAQ__kav
As a workaround, cast the input array to the DML statement from an array of FAQ__kav articles to an array of the generic sObject
type as follows:
public void DMLOperation() {
FAQ__kav[] articles = [SELECT id FROM FAQ__kav WHERE PublishStatus = 'Draft' and
Language = 'en_US'];
update (sObject[]) articles;
}
Locking Records
When an sObject record is locked, no other client or user is allowed to make updates either through code or the Salesforce user interface.
The client locking the records can perform logic on the records and make updates with the guarantee that the locked records won’t be
changed by another client during the lock period.
161
Apex Developer Guide Working with Data in Apex
IN THIS SECTION:
Locking Statements
In Apex, you can use FOR UPDATE to lock sObject records while they’re being updated in order to prevent race conditions and
other thread safety problems.
Locking in a SOQL For Loop
Avoiding Deadlocks
Locking Statements
In Apex, you can use FOR UPDATE to lock sObject records while they’re being updated in order to prevent race conditions and other
thread safety problems.
While an sObject record is locked, no other client or user is allowed to make updates either through code or the Salesforce user interface.
The client locking the records can perform logic on the records and make updates with the guarantee that the locked records won’t be
changed by another client during the lock period. The lock gets released when the transaction completes.
To lock a set of sObject records in Apex, embed the keywords FOR UPDATE after any inline SOQL statement. For example, the following
statement, in addition to querying for two accounts, also locks the accounts that are returned:
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];
Note: You can’t use the ORDER BY keywords in any SOQL query that uses locking.
Locking Considerations
• While the records are locked by a client, the locking client can modify their field values in the database in the same transaction. Other
clients have to wait until the transaction completes and the records are no longer locked before being able to update the same
records. Other clients can still query the same records while they’re locked.
• If you attempt to lock a record currently locked by another client, your process waits a maximum of 10 seconds for the lock to be
released before acquiring a new lock. If the wait time exceeds 10 seconds, a QueryException is thrown. Similarly, if you attempt
to update a record currently locked by another client and the lock isn’t released within a maximum of 10 seconds, a DmlException
is thrown.
• If a client attempts to modify a locked record, the update operation can succeed if the lock gets released within a short amount of
time after the update call was made. In this case, it’s possible that the updates overwrite changes made by the locking client if the
second client obtained an old copy of the record. To prevent the overwrite from happening, the second client must lock the record
first. The locking process returns a fresh copy of the record from the database through the SELECT statement. The second client
can use this copy to make new updates.
• The record locks that are obtained in Apex via FOR UPDATE clause are automatically released when making callouts. The information
is logged in the debug log and the logged message includes the most recently locked entity type. For example:
FOR_UPDATE_LOCKS_RELEASE FOR UPDATE locks released due to a callout. The most recent
lock was Account. Use caution while making callouts in contexts where FOR UPDATE queries could have been previously
executed.
• When you perform a DML operation on one record, related records are locked in addition to the record in question.
Warning: Use care when setting locks in your Apex code. See Avoiding Deadlocks.
162
Apex Developer Guide Working with Data in Apex
As discussed in SOQL For Loops, the example above corresponds internally to calls to the query() and queryMore() methods
in the SOAP API.
Note that there is no commit statement. If your Apex trigger completes successfully, any database changes are automatically committed.
If your Apex trigger does not complete successfully, any changes made to the database are rolled back.
Avoiding Deadlocks
Apex has the possibility of deadlocks, as does any other procedural logic language involving updates to multiple database tables or
rows. To avoid such deadlocks, the Apex runtime engine:
1. First locks sObject parent records, then children.
2. Locks sObject records in order of ID when multiple records of the same type are being edited.
As a developer, use care when locking rows to ensure that you are not introducing deadlocks. Verify that you are using standard deadlock
avoidance techniques by accessing tables and rows in the same order from all locations in an application.
SOQL Statements
SOQL statements evaluate to a list of sObjects, a single sObject, or an Integer for count method queries.
For example, you could retrieve a list of accounts that are named Acme:
List<Account> aa = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];
You can also create new objects from SOQL queries on existing ones. This example creates a new contact for the first account with the
number of employees greater than 10.
Contact c = new Contact(Account = [SELECT Name FROM Account
WHERE NumberOfEmployees > 10 LIMIT 1]);
c.FirstName = 'James';
c.LastName = 'Yoyce';
The newly created object contains null values for its fields, which must be set.
163
Apex Developer Guide Working with Data in Apex
The count method can be used to return the number of rows returned by a query. The following example returns the total number
of contacts with the last name of Weissman:
Integer i = [SELECT COUNT() FROM Contact WHERE LastName = 'Weissman'];
SOQL limits apply when executing SOQL queries. See Execution Governors and Limits.
For a full description of SOQL query syntax, see the Salesforce SOQL and SOSL Reference Guide.
SOSL Statements
SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type. The result
lists are always returned in the same order as they were specified in the SOSL query. If a SOSL query doesn’t return any records for a
specified sObject type, the search results include an empty list for that sObject.
For example, you can return a list of accounts, contacts, opportunities, and leads that begin with the phrase map:
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name),
Contact, Opportunity, Lead];
Note: The syntax of the FIND clause in Apex differs from the syntax of the FIND clause in SOAP API and REST API:
• In Apex, the value of the FIND clause is demarcated with single quotes. For example:
FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead
Note: Apex that is running in system mode ignores field-level security while scanning for a match using IN ALL
FIELDS.
• In the API, the value of the FIND clause is demarcated with braces. For example:
FIND {map*} IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead
From searchList, you can create arrays for each object returned:
Account [] accounts = ((List<Account>)searchList[0]);
Contact [] contacts = ((List<Contact>)searchList[1]);
Opportunity [] opportunities = ((List<Opportunity>)searchList[2]);
Lead [] leads = ((List<Lead>)searchList[3]);
SOSL limits apply when executing SOSL queries. See Execution Governors and Limits.
Note: The 4,000 characters limit for WHERE clause strings doesn’t apply to SOQL queries in Apex if the WHERE clause includes
the IN operator.
For a full description of SOSL query syntax, see the Salesforce SOQL and SOSL Reference Guide.
IN THIS SECTION:
1. Working with SOQL and SOSL Query Results
2. Accessing sObject Fields Through Relationships
3. Understanding Foreign Key and Parent-Child Relationship SOQL Queries
164
Apex Developer Guide Working with Data in Apex
The following is the same code example rewritten so it does not produce a runtime error. Note that Name has been added as part of
the select statement, after Id.
insert new Account(Name = 'Singha');
Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1];
// Note that name is now selected
String name = [SELECT Id, Name FROM Account WHERE Name = 'Singha' LIMIT 1].Name;
Even if only one sObject field is selected, a SOQL or SOSL query always returns data as complete records. Consequently, you must
dereference the field in order to access it. For example, this code retrieves an sObject list from the database with a SOQL query, accesses
the first account record in the list, and then dereferences the record's AnnualRevenue field:
Double rev = [SELECT AnnualRevenue FROM Account
WHERE Name = 'Acme'][0].AnnualRevenue;
The only situation in which it is not necessary to dereference an sObject field in the result of an SOQL query, is when the query returns
an Integer as the result of a COUNT operation:
Integer i = [SELECT COUNT() FROM Account];
165
Apex Developer Guide Working with Data in Apex
Note: To provide the most complete example, this code uses some elements that are described later in this guide:
• For information on insert and update, see Insert Statement and Update Statement.
Note: The expression c.Account.Name, and any other expression that traverses a relationship, displays slightly different
characteristics when it is read as a value than when it is modified:
• When being read as a value, if c.Account is null, then c.Account.Name evaluates to null, but does not yield a
NullPointerException. This design allows developers to navigate multiple relationships without the tedium of having
to check for null values.
• When being modified, if c.Account is null, then c.Account.Name does yield a NullPointerException.
In SOSL, you would access data for the inserted contact in a similar way to the SELECT statement used in the previous SOQL example.
List<List<SObject>> searchList = [FIND 'Acme' IN ALL FIELDS RETURNING
Contact(id,Account.Name)]
In addition, the sObject field key can be used with insert, update, or upsert to resolve foreign keys by external ID. For example:
Account refAcct = new Account(externalId__c = '12345');
insert c;
166
Apex Developer Guide Working with Data in Apex
This inserts a new contact with the AccountId equal to the account with the external_id equal to ‘12345’. If there is no such
account, the insert fails.
Tip: The following code is equivalent to the code above. However, because it uses a SOQL query, it is not as efficient. If this code
was called multiple times, it could reach the execution limit for the maximum number of SOQL queries. For more information on
execution limits, see Execution Governors and Limits on page 321.
Account refAcct = [SELECT Id FROM Account WHERE externalId__c='12345'];
insert c;
Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example:
for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts)
FROM Account
WHERE Name = 'Acme']) {
Contact[] cons = a.Contacts;
}
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.
167
Apex Developer Guide Working with Data in Apex
Aggregate functions become a more powerful tool to generate reports when you use them with a GROUP BY clause. For example,
you could find the average Amount for all your opportunities by campaign.
AggregateResult[] groupedResults
= [SELECT CampaignId, AVG(Amount)
FROM Opportunity
GROUP BY CampaignId];
for (AggregateResult ar : groupedResults) {
System.debug('Campaign ID' + ar.get('CampaignId'));
System.debug('Average amount' + ar.get('expr0'));
}
Any aggregated field in a SELECT list that does not have an alias automatically gets an implied alias with a format expri, where i
denotes the order of the aggregated fields with no explicit aliases. The value of i starts at 0 and increments for every aggregated field
with no explicit alias. For more information, see Using Aliases with GROUP BY in the Salesforce SOQL and SOSL Reference Guide.
Note: Queries that include aggregate functions are still subject to the limit on total number of query rows. All aggregate functions
other than COUNT() or COUNT(fieldname) include each row used by the aggregation as a query row for the purposes
of limit tracking.
For COUNT() or COUNT(fieldname) queries, limits are counted as one query row, unless the query contains a GROUP BY
clause, in which case one query row per grouping is consumed.
Instead, use a SOQL query for loop as in one of the following examples:
// Use this format if you are not executing DML statements
// within the for loop
for (Account a : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%']) {
// Your code without DML statements here
}
// Use this format for efficiency if you are executing DML statements
// within the for loop
for (List<Account> accts : [SELECT Id, Name FROM Account
WHERE Name LIKE 'Acme%']) {
for (Account a : accts) {
// Your code here
}
update accts;
}
168
Apex Developer Guide Working with Data in Apex
Note: Using the SOQL query within the for loop reduces the possibility of reaching the limit on heap size. However, this approach
can result in more CPU cycles being used with increased DML calls. For more information, see SOQL For Loops Versus Standard
SOQL Queries.
The following example demonstrates a SOQL query for loop that’s used to mass update records. Suppose that you want to change
the last name of a contact in records for contacts whose first and last names match specified criteria:
public void massUpdate() {
for (List<Contact> contacts:
[SELECT FirstName, LastName FROM Contact]) {
for(Contact c : contacts) {
if (c.FirstName == 'Barbara' &&
c.LastName == 'Gordon') {
c.LastName = 'Wayne';
}
}
update contacts;
}
}
Instead of using a SOQL query in a for loop, the preferred method of mass updating records is to use batch Apex, which minimizes
the risk of hitting governor limits.
For more information, see SOQL For Loops on page 175.
• Fields not indexed by default are automatically indexed when the Salesforce optimizer recognizes that an index can improve
performance for frequently run queries.
• Salesforce Support can add custom indexes on request for customers.
169
Apex Developer Guide Working with Data in Apex
• A custom index can't be created on these types of fields: multi-select picklists, currency fields in a multicurrency organization,
long text fields, some formula fields, and binary fields (fields of type blob, file, or encrypted text.) New data types, typically complex
ones, are periodically added to Salesforce, and fields of these types don’t always allow custom indexing.
• You can’t create custom indexes on formula fields that include invocations of the TEXT function on picklist fields.
• Typically, a custom index isn’t used in these cases.
– The queried values exceed the system-defined threshold.
– The filter operator is a negative operator such as NOT EQUAL TO (or !=), NOT CONTAINS, and NOT STARTS
WITH.
– The CONTAINS operator is used in the filter, and the number of rows to be scanned exceeds 333,333. The CONTAINS
operator requires a full scan of the index. This threshold is subject to change.
– You’re comparing with an empty value (Name != '').
However, there are other complex scenarios in which custom indexes can’t be used. Contact your Salesforce representative if
your scenario isn't covered by these cases or if you need further assistance with non-selective queries.
The WHERE clause is on an indexed field (Id). If SELECT COUNT() FROM Account WHERE Id IN (<list of
account IDs>) returns fewer records than the selectivity threshold, the index on Id is used. This index is typically used when
the list of IDs contains only a few records.
Query 2:
SELECT Id FROM Account WHERE Name != ''
Since Account is a large object even though Name is indexed (primary key), this filter returns most of the records, making the query
non-selective.
Query 3:
SELECT Id FROM Account WHERE Name != '' AND CustomField__c = 'ValueA'
Here we have to see if any filter, when considered individually, is selective. As we saw in the previous example, the first filter isn't
selective. So let's focus on the second one. If the count of records returned by SELECT COUNT() FROM Account WHERE
CustomField__c = 'ValueA' is lower than the selectivity threshold, and CustomField__c is indexed, the query is selective.
// 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.
170
Apex Developer Guide Working with Data in Apex
This usage is supported with the following Apex types, methods, or operators:
• Database.query method.
• Safe Navigation Operator. See Safe Navigation Operator.
• Null Coalescing Operator. See Null Coalescing Operator.
• Map.values.
Warning: Although currently supported, Salesforce recommends against using this feature with Map.values.
/* getThreadTags
*
* a quick method to pull tags not in the existing list
*
*/
public static webservice List<String>
getThreadTags(String threadId, List<String> tags) {
system.debug(LoggingLevel.Debug,tags);
for(CSO_CaseThread_Tag__c t :
[SELECT Name FROM CSO_CaseThread_Tag__c
WHERE Thread__c = :threadId AND
Thread__c != null])
{
tagSet.add(t.Name);
}
for(String x : origTagSet) {
// return a minus version of it so the UI knows to clear it
if(!tagSet.contains(x)) retVals.add('-' + x);
}
for(String x : tagSet) {
// return a plus version so the UI knows it's new
if(!origTagSet.contains(x)) retvals.add('+' + x);
}
171
Apex Developer Guide Working with Data in Apex
return retVals;
}
}
Another approach would be to use the TYPEOF clause in the SOQL SELECT statement. This example also queries Events that are
related to an Account or Opportunity via the What field.
List<Event> events = [SELECT TYPEOF What WHEN Account THEN Phone WHEN Opportunity THEN
Amount END FROM Event];
These queries return a list of sObjects where the relationship field references the desired object types.
If you need to access the referenced object in a polymorphic relationship, you can use the instanceof keyword to determine the object
type. The following example uses instanceof to determine whether an Account or Opportunity is related to an Event.
Event myEvent = eventFromQuery;
if (myEvent.What instanceof Account) {
// myEvent.What references an Account, so process accordingly
} else if (myEvent.What instanceof Opportunity) {
// myEvent.What references an Opportunity, so process accordingly
}
Note that you must assign the referenced sObject that the query returns to a variable of the appropriate type before you can pass it to
another method. The following example
1. Queries for User or Group owners of Merchandise__c custom objects using a SOQL query with a TYPEOF clause
2. Uses instanceof to determine the owner type
3. Assigns the owner objects to User or Group type variables before passing them to utility methods
public class PolymorphismExampleClass {
172
Apex Developer Guide Working with Data in Apex
// A simple bind
B = [SELECT Id FROM Account WHERE Id = :A.Id];
String s = 'XXX';
173
Apex Developer Guide Working with Data in Apex
// A limit bind
Integer i = 1;
B = [SELECT Id FROM Account LIMIT :i];
// An OFFSET bind
Integer offsetVal = 10;
List<Account> offsetList = [SELECT Id FROM Account OFFSET :offsetVal];
174
Apex Developer Guide Working with Data in Apex
Opportunity,
Lead
WITH DIVISION =:myString4
LIMIT :myInt5];
Note: Apex bind variables aren’t supported for the units parameter in the DISTANCE function. This query doesn’t work.
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.
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 code expressions in their WHERE clauses using the :
syntax. For example:
String s = 'Acme';
for (Account a : [SELECT Id, Name from Account
where Name LIKE :(s+'%')]) {
// Your code
}
The following example combines creating a list from a SOQL query, with the DML update method.
// Create a list of account records from a SOQL query
List<Account> accs = [SELECT Id, Name FROM Account WHERE Name = 'Siebel'];
175
Apex Developer Guide Working with Data in Apex
// 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']) {
176
Apex Developer Guide Working with Data in Apex
j = tmp.size();
i++;
}
System.assert(j == 3); // The lt should have contained the three accounts
// named 'yyy'
System.assert(i == 1); // Since a single batch can hold up to 200 records and,
// only three records should have been returned, the
// loop should have executed only once
Note:
• The break and continue keywords can be used in both types of inline query for loop formats. When using the sObject
list format, continue skips to the next list of sObjects.
• DML statements can only process up to 10,000 records at a time, and sObject list for loops process records in batches of
200. Consequently, if you’re inserting, updating, or deleting more than one record per returned record in an sObject list for
loop, it’s possible to encounter runtime limit’s errors. See Execution Governors and Limits.
• You may get a QueryException in a SOQL for loop with the message Aggregate query has too many
rows for direct assignment, use FOR loop. This exception is sometimes thrown when accessing a large
set of child records (200 or more) of a retrieved sObject inside the loop, or when getting the size of such a record set. For
example, the query in the following SOQL for loop retrieves child contacts for a particular account. If this account contains
more than 200 child contacts, the statements in the for loop cause an exception.
for (Account acct : [SELECT Id, Name, (SELECT Id, Name FROM Contacts)
FROM Account WHERE Id IN ('<ID value>')]) {
List<Contact> contactList = acct.Contacts; // Causes an error
Integer count = acct.Contacts.size(); // Causes an error
}
To avoid getting this exception, use a for loop to iterate over the child records, as follows.
for (Account acct : [SELECT Id, Name, (SELECT Id, Name FROM Contacts)
FROM Account WHERE Id IN ('<ID value>')]) {
Integer count=0;
for (Contact c : acct.Contacts) {
count++;
}
}
sObject Collections
You can manage sObjects in lists, sets, and maps.
IN THIS SECTION:
Lists of sObjects
Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
Sorting Lists of sObjects
Using the List.sort method, you can sort lists of sObjects.
177
Apex Developer Guide Working with Data in Apex
Lists of sObjects
Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
You can use a list to store sObjects. Lists are useful when working with SOQL queries. SOQL queries return sObject data and this data
can be stored in a list of sObjects. Also, you can use lists to perform bulk operations, such as inserting a list of sObjects with one call.
To declare a list of sObjects, use the List keyword followed by the sObject type within <> characters. For example:
// Create an empty list of Accounts
List<Account> myList = new List<Account>();
Bulk Processing
You can bulk-process a list of sObjects by passing a list to the DML operation. This example shows how you can insert a list of accounts.
// Define the list
List<Account> acctList = new List<Account>();
// Create account sObjects
Account a1 = new Account(Name='Account1');
Account a2 = new Account(Name='Account2');
// Add accounts to the list
acctList.add(a1);
acctList.add(a2);
178
Apex Developer Guide Working with Data in Apex
Note: If you perform a bulk insert of Knowledge article versions, make the ownerId of all records the same.
Record ID Generation
Apex automatically generates IDs for each object in an sObject list that was inserted or upserted using DML. Therefore, a list that contains
more than one instance of an sObject cannot be inserted or upserted 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 {
These examples also use the array notation with sObject lists.
Example Description
Defines an Account list with no elements.
List<Account> accts = new Account[]{};
179
Apex Developer Guide Working with Data in Apex
Example Description
Defines the Contact list with a new list.
List<Contact> contacts = new List<Contact>
(otherList);
3. Standard fields, starting with the fields that come first in alphabetical order, except for the Id and Name fields.
For example, if two accounts have the same name, the first standard field used for sorting is AccountNumber.
4. Custom fields, starting with the fields that come first in alphabetical order.
For example, suppose two accounts have the same name and identical standard fields, and there are two custom fields, FieldA and
FieldB, the value of FieldA is used first for sorting.
Not all steps in this sequence are necessarily carried out. For example, a list containing two sObjects of the same type and with unique
Name values is sorted based on the Name field and sorting stops at step 2. Otherwise, if the names are identical or the sObject doesn’t
have a Name field, sorting proceeds to step 3 to sort by standard fields.
For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.
Here’s an example of sorting a list of Account sObjects. This example shows how the Name field is used to place the Acme account
ahead of the two sForce accounts in the list. Since there are two accounts named sForce, the Industry field is used to sort these remaining
accounts because the Industry field comes before the Site field in alphabetical order.
Account[] acctList = new List<Account>();
acctList.add( new Account(
Name='sForce',
Industry='Biotechnology',
Site='Austin'));
acctList.add(new Account(
Name='sForce',
180
Apex Developer Guide Working with Data in Apex
Industry='Agriculture',
Site='New York'));
acctList.add(new Account(
Name='Acme'));
System.debug(acctList);
acctList.sort();
Assert.areEqual('Acme', acctList[0].Name);
Assert.areEqual('sForce', acctList[1].Name);
Assert.areEqual('Agriculture', acctList[1].Industry);
Assert.areEqual('sForce', acctList[2].Name);
Assert.areEqual('Biotechnology', acctList[2].Industry);
System.debug(acctList);
This example is similar to the previous one, except that it uses the Merchandise__c custom object. This example shows how the Name
field is used to place the Notebooks merchandise ahead of Pens in the list. Because there are two merchandise sObjects with the Name
field value of Pens, the Description field is used to sort these remaining merchandise items. The Description field is used for sorting
because it comes before the Price and Total_Inventory fields in alphabetical order.
Merchandise__c[] merchList = new List<Merchandise__c>();
merchList.add( new Merchandise__c(
Name='Pens',
Description__c='Red pens',
Price__c=2,
Total_Inventory__c=1000));
merchList.add( new Merchandise__c(
Name='Notebooks',
Description__c='Cool notebooks',
Price__c=3.50,
Total_Inventory__c=2000));
merchList.add( new Merchandise__c(
Name='Pens',
Description__c='Blue pens',
Price__c=1.75,
Total_Inventory__c=800));
System.debug(merchList);
merchList.sort();
Assert.areEqual('Notebooks', merchList[0].Name);
Assert.areEqual('Pens', merchList[1].Name);
Assert.areEqual('Blue pens', merchList[1].Description__c);
Assert.areEqual('Pens', merchList[2].Name);
Assert.areEqual('Red pens', merchList[2].Description__c);
System.debug(merchList);
181
Apex Developer Guide Working with Data in Apex
Example: This example implements the Comparator interface to compare two opportunities based on the Amount field.
public class OpportunityComparator implements Comparator<Opportunity> {
public Integer compare(Opportunity o1, Opportunity o2) {
// The return value of 0 indicates that both elements are equal.
Integer returnValue = 0;
This test sorts a list of Comparator objects and verifies that the list elements are sorted by the opportunity amount.
@isTest
private class OpportunityComparator_Test {
@isTest
static void sortViaComparator() {
// Add the opportunity wrapper objects to a list.
List<Opportunity> oppyList = new List<Opportunity>();
Date closeDate = Date.today().addDays(10);
oppyList.add( new Opportunity(
Name='Edge Installation',
CloseDate=closeDate,
StageName='Prospecting',
Amount=50000));
oppyList.add( new Opportunity(
Name='United Oil Installations',
CloseDate=closeDate,
StageName='Needs Analysis',
Amount=100000));
182
Apex Developer Guide Working with Data in Apex
Example: This example shows how to create a wrapper Comparable class for Opportunity. The implementation of the
compareTo method in this class compares two opportunities based on the Amount field—the class member variable contained
in this instance, and the opportunity object passed into the method.
public class OpportunityWrapper implements Comparable {
// Constructor
public OpportunityWrapper(Opportunity op) {
// Guard against wrapping a null
if(op == null) {
Exception ex = new NullPointerException();
ex.setMessage('Opportunity argument cannot be null');
throw ex;
}
oppy = op;
}
183
Apex Developer Guide Working with Data in Apex
This test sorts a list of OpportunityWrapper objects and verifies that the list elements are sorted by the opportunity amount.
@isTest
private class OpportunityWrapperTest {
static testmethod void test1() {
// Add the opportunity wrapper objects to a list.
OpportunityWrapper[] oppyList = new List<OpportunityWrapper>();
Date closeDate = Date.today().addDays(10);
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='Edge Installation',
CloseDate=closeDate,
StageName='Prospecting',
Amount=50000)));
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='United Oil Installations',
CloseDate=closeDate,
StageName='Needs Analysis',
Amount=100000)));
oppyList.add( new OpportunityWrapper(new Opportunity(
Name='Grand Hotels SLA',
CloseDate=closeDate,
StageName='Prospecting',
Amount=25000)));
184
Apex Developer Guide Working with Data in Apex
}
}
SEE ALSO:
Apex Reference Guide: Collator Class
Apex Reference Guide: Comparable Interface
Apex Reference Guide: Comparator Interface
Sets of Objects
Sets can contain sObjects among other types of elements.
Sets contain unique elements. Uniqueness of sObjects is determined by comparing the objects’ fields. For example, if you try to add two
accounts with the same name to a set, with no other fields set, only one sObject is added to the set.
// Create two accounts, a1 and a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount');
If you add a description to one of the accounts, it is considered unique and both accounts are added to the set.
// Create two accounts, a1 and a2, and add a description to a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount', description='My test account');
185
Apex Developer Guide Working with Data in Apex
Warning: If set elements are objects, and these objects change after being added to the collection, they won’t be found anymore
when using, for example, the contains or containsAll methods, because of changed field values.
Maps of sObjects
Map keys and values can be of any data type, including sObject types, such as Account.
Maps can hold sObjects both in their keys and values. A map key represents a unique value that maps to a map value. For example, a
common key would be an ID that maps to an account (a specific sObject type). This example shows how to define a map whose keys
are of type ID and whose values are of type Account.
Map<ID, Account> m = new Map<ID, Account>();
As with primitive types, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the
curly braces, specify the key first, then specify the value for that key using =>. This example creates a map of integers to accounts lists
and adds one entry using the account list created earlier.
Account[] accs = new Account[5]; // Account[] is synonymous with List<Account>
Map<Integer, List<Account>> m4 = new Map<Integer, List<Account>>{1 => accs};
Maps allow sObjects in their keys. You must use sObjects in the keys only when the sObject field values won’t change.
One common usage of this map type is for in-memory “joins” between two tables.
Note: RecentlyViewed records for users who are members of several communities can’t be retrieved automatically into a map
via Apex. This is because records of a user with different networks can result in duplicate IDs that maps don’t support. For more
information, see RecentlyViewed.
186
Apex Developer Guide Working with Data in Apex
IN THIS SECTION:
sObject Map Considerations
// Insert a1.
// This causes the ID field on a1 to be auto-filled
insert a1;
// Id field is now populated.
System.assertNotEquals(null, a1.Id);
Another scenario where sObject fields are autofilled is in triggers, for example, when using before and after insert triggers for an sObject.
If those triggers share a static map defined in a class, and the sObjects in Trigger.New are added to this map in the before trigger,
the sObjects in Trigger.New in the after trigger aren’t found in the map because the two sets of sObjects differ by the fields that
187
Apex Developer Guide Working with Data in Apex
are autofilled. The sObjects in Trigger.New in the after trigger have system fields populated after insertion, namely: ID, CreatedDate,
CreatedById, LastModifiedDate, LastModifiedById, and SystemModStamp.
Dynamic Apex
Dynamic Apex enables developers to create more flexible applications by providing them with the ability to:
• Access sObject and field describe information
Describe information provides metadata information about sObject and field properties. For example, the describe information for
an sObject includes whether that type of sObject supports operations like create or undelete, the sObject's name and label, the
sObject's fields and child objects, and so on. The describe information for a field includes whether the field has a default value,
whether it is a calculated field, the type of the field, and so on.
Note that describe information provides information about objects in an organization, not individual records.
• 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 AppExchange.
IN THIS SECTION:
1. Understanding Apex Describe Information
2. Using Field Tokens
3. Understanding Describe Information Permissions
4. Describing sObjects Using Schema Method
5. Describing Tabs Using Schema Methods
6. Accessing All sObjects
7. Accessing All Data Categories Associated with an sObject
8. Dynamic SOQL
9. Dynamic SOSL
10. Dynamic DML
188
Apex Developer Guide Working with Data in Apex
• Describe result—an object of type Schema.DescribeSObjectResult that contains all the describe properties for the
sObject or field. Describe result objects are not serializable, and are validated at runtime. This result object is returned when performing
the describe, using either the sObject token or the describeSObjects method.
// Get the field describe result for the Name field on the Account object
Schema.DescribeFieldResult dfr = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(dfr.getSObjectField() == Account.Name);
The following algorithm shows how you can work with describe information in Apex:
1. Generate a list or map of tokens for the sObjects in your organization (see Accessing All sObjects.)
2. Determine the sObject you need to access.
3. Generate the describe result for the sObject.
4. If necessary, generate a map of field tokens for the sObject (see Accessing All Field Describe Results for an sObject.)
5. Generate the describe result for the field the code needs to access.
189
Apex Developer Guide Working with Data in Apex
This example can be used to determine whether an sObject or a list of sObjects is of a particular type:
// Create a generic sObject variable s
SObject s = Database.query('SELECT Id FROM Account LIMIT 1');
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.
The following example uses the Schema sObjectType static member variable:
Schema.DescribeSObjectResult dsr = Schema.SObjectType.Account;
For more information about the methods available with the sObject describe result, see DescribeSObjectResultClass.
SEE ALSO:
DescribeSObjectResult.fields()
DescribeSObjectResult.fieldsets()
190
Apex Developer Guide Working with Data in Apex
In the following example, the field token is returned from the field describe result:
// Get the describe result for the Name field on the Account object
Schema.DescribeFieldResult dfr = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(dfr.getSObjectField() == Account.Name);
Note: Field tokens aren't available for person accounts. If you access Schema.Account.fieldname, you get an exception
error. Instead, specify the field name as a string.
In the example above, the system uses special parsing to validate that the final member variable (Name) is valid for the specified sObject
at compile time. When the parser finds the fields member variable, it looks backwards to find the name of the sObject (Account).
It validates that the field name following the fields member variable is legitimate. The fields member variable only works when
used in this manner.
Note: Don’t use the fields member variable without also using either a field member variable name or the getMap method.
For more information on getMap, see the next section.
For more information about the methods available with a field describe result, see DescribeFieldResultClass.
191
Apex Developer Guide Working with Data in Apex
Note: The value type of this map is not a field describe result. Using the describe results would take too many system resources.
Instead, it is a map of tokens that you can use to find the appropriate field. After you determine the field, generate the describe
result for it.
The map has the following characteristics:
• It is dynamic, that is, it is generated at runtime on the fields for that sObject.
• All field names are case insensitive.
• The keys use namespaces as required.
• The keys reflect whether the field is a custom object.
SEE ALSO:
DescribeSObjectResult.fields()
DescribeSObjectResult.fieldsets()
SEE ALSO:
Anonymous Blocks
What is a Package?
192
Apex Developer Guide Working with Data in Apex
SEE ALSO:
DescribeSObjectResult.fields()
DescribeSObjectResult.fieldsets()
// Iterate through each tab set describe for each app and display the info
for(DescribeTabSetResult tsr : tabSetDesc) {
String appLabel = tsr.getLabel();
System.debug('Label: ' + appLabel);
System.debug('Logo URL: ' + tsr.getLogoUrl());
System.debug('isSelected: ' + tsr.isSelected());
String ns = tsr.getNamespace();
193
Apex Developer Guide Working with Data in Apex
if (ns == '') {
System.debug('The ' + appLabel + ' app has no namespace defined.');
}
else {
System.debug('Namespace: ' + ns);
}
// Schema.DescribeColorResult[getColor=236FBD;getContext=primary;getTheme=theme2;])
// DEBUG|getIconUrl: https://MyDomainName.my.salesforce.com/img/icon/accounts32.png
// DEBUG|getIcons:
(Schema.DescribeIconResult[getContentType=image/png;getHeight=32;getTheme=theme3;
//
getUrl=https://MyDomainName.my.salesforce.com/img/icon/accounts32.png;getWidth=32;],
// Schema.DescribeIconResult[getContentType=image/png;getHeight=16;getTheme=theme3;
//
getUrl=https://MyDomainName.my.salesforce.com/img/icon/accounts16.png;getWidth=16;])
// DEBUG|getMiniIconUrl: https://MyDomainName.my.salesforce.com/img/icon/accounts16.png
// DEBUG|getSobjectName: Account
// DEBUG|getUrl: https://MyDomainName.my.salesforce.com/001/o
// DEBUG|isCustom: false
194
Apex Developer Guide Working with Data in Apex
Note: If the getGlobalDescribe method is called from an installed managed package, it returns sObject names and tokens
for Chatter sObjects, such as NewsFeed and UserProfileFeed, even if Chatter is not enabled in the installing organization. This is
not true if the getGlobalDescribe method is called from a class not within an installed managed package.
195
Apex Developer Guide Working with Data in Apex
• Make sure the Regions data category group is assigned to Salesforce Knowledge.
For more information on creating data category groups, see “Create and Modify Category Groups” in the Salesforce online help. For more
information on answers, see “Answers Overview” in the Salesforce online help.
List<DescribeDataCategoryGroupResult> describeCategoryResult;
try {
//Creating the list of sobjects to use for the describe
//call
List<String> objType = new List<String>();
objType.add('KnowledgeArticleVersion');
objType.add('Question');
//Describe Call
describeCategoryResult = Schema.describeDataCategoryGroups(objType);
//Getting description
singleResult.getDescription();
return describeCategoryResult;
}
}
196
Apex Developer Guide Working with Data in Apex
describeCategoryResult = Schema.describeDataCategoryGroups(objType);
//describeDataCategoryGroupStructures()
describeCategoryStructureResult =
Schema.describeDataCategoryGroupStructures(pairs, false);
197
Apex Developer Guide Working with Data in Apex
category.getChildCategories();
}
}
} catch (Exception e){
}
return describeCategoryStructureResult;
}
198
Apex Developer Guide Working with Data in Apex
System.assert(objectNames.contains('KnowledgeArticleVersion')
|| objectNames.contains('Question'),
'Incorrect sObject was returned: ' + objectNames);
}
}
}
This example tests the describeDataCategoryGroupStructures method. It ensures that the returned category group,
categories and associated objects are correct.
@isTest
private class DescribeDataCategoryGroupStructuresTest {
public static testMethod void getDescribeDataCategoryGroupStructureResultsTest(){
List<Schema.DescribeDataCategoryGroupStructureResult> describeResult =
DescribeDataCategoryGroupStructures.getDescribeDataCategoryGroupStructureResults();
System.assert(describeResult.size() == 2,
'The results should only contain 2 results: ' + describeResult.size());
199
Apex Developer Guide Working with Data in Apex
topLevelCategories[0].getName() == world.getName());
Dynamic SOQL
Dynamic SOQL refers to the creation of a SOQL string at run time with Apex code. Dynamic SOQL enables you to create more flexible
applications. For example, you can create a search based on input from an end user or update records with varying field names.
To create a dynamic SOQL query at run time, use the Database.query or Database.queryWithBinds methods, in one
of the following ways.
• Return a single sObject when the query returns a single record:
sObject s = Database.query(string);
• Return a list of sObjects when the query returns more than a single record:
200
Apex Developer Guide Working with Data in Apex
The Database.query and Database.queryWithBinds methods 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.
With API version 55.0 and later, as part of the User Mode for Database Operations feature, use the accessLevel parameter to run
the query operation in user or system mode. The accessLevel parameter specifies whether the method runs in system mode
(AccessLevel.SYSTEM_MODE) or user mode (AccessLevel.USER_MODE). In system mode, the object and field-level
permissions of the current user are ignored, and the record sharing rules are controlled by the class sharing keywords. In user mode, the
object permissions, field-level security, and sharing rules of the current user are enforced. System mode is the default.
Dynamic SOQL results can be specified as concrete sObjects, such as Account or MyCustomObject__c, or as the generic sObject data
type. At run time, the system validates that the type of the query matches the declared type of the variable. If the query doesn’t return
the correct sObject type, a run-time error is thrown. Therefore, you don’t have to cast from a generic sObject to a concrete sObject.
Dynamic SOQL queries have the same governor limits as static queries. For more information on governor limits, see Execution Governors
and Limits on page 321.
For a full description of SOQL query syntax, see Salesforce Object Query Language (SOQL) in the SOQL and SOSL Reference.
However, unlike inline SOQL, you can’t use bind variable fields in the query string with Database.query. The following example
isn’t supported and results in a Variable does not exist error.
MyCustomObject__c myVariable = new MyCustomObject__c(field1__c ='TestField');
List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c
= :myVariable.field1__c');
You can instead resolve the variable field into a string and use the string in your dynamic SOQL query:
String resolvedField1 = myVariable.field1__c;
List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c
= :resolvedField1');
(API version 57.0 and later) Another option is to use the Database.queryWithBinds method. With this method, bind variables
in the query are resolved from a Map parameter directly with a key, rather than from Apex code variables. This removes the need for the
variables to be in scope when the query is executed. This example shows a SOQL query that uses a bind variable for an Account name;
its value is passed in with the acctBinds Map.
Map<String, Object> acctBinds = new Map<String, Object>{'acctName' => 'Acme Corporation'};
List<Account> accts =
Database.queryWithBinds('SELECT Id FROM Account WHERE Name = :acctName',
acctBinds,
AccessLevel.USER_MODE);
These considerations apply when u