Salesforce Apex Developer Guide 2
Salesforce Apex Developer Guide 2
© Copyright 2000–2022 salesforce.com, inc. All rights reserved. Salesforce is a registered trademark of salesforce.com, inc.,
as are other names and marks. Other marks appearing herein may be trademarks of their respective owners.
@salesforcedocs
Last updated: April 21, 2022
CONTENTS
APEX DEVELOPER GUIDE 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.
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control Introducing Apex
statements on the Salesforce Platform server, in conjunction with calls to the API. This guide introduces you to the Apex development Apex code is the first multitenant, on-demand programming language for developers interested in building the next generation of
process and provides valuable information on learning, writing, deploying and testing Apex. business applications. Apex revolutionizes the way developers create on-demand applications.
For reference information on Apex classes, interfaces, exceptions and so on, see Apex Reference Guide. 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(),
IN THIS SECTION: update() or upsert(), from client-side programs.
Getting Started with Apex These client-side programs, typically written in Java, JavaScript, .NET, or other programming languages, grant organizations more flexibility
Learn about the Apex development lifecycle. Follow a step-by-step tutorial to create an Apex class and trigger, and deploy them to in their customizations. However, because the controlling logic for these client-side programs is not located on Salesforce servers, they
a production organisation. 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.
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:
1 2
Apex Developer Guide Introducing Apex Apex Developer Guide Introducing Apex
What is Apex? • Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject
records
Apex is a strongly typed, object-oriented programming language that allows developers to execute
EDITIONS • Looping that allows for bulk processing of multiple records at a time
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 • Locking syntax that prevents record update conflicts
Available in: Salesforce
to add business logic to most system events, including button clicks, related record updates, and Classic (not available in all • Custom public API calls that can be built from stored Apex methods
Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects. orgs) and Lightning • Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex
Experience
Easy to use
Available in: Enterprise, Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax, loop syntax,
Performance, Unlimited, object and array notation. Where Apex introduces new elements, it uses syntax and semantics that are easy to understand and
Developer, and encourage efficient use of the Lightning Platform. Therefore, Apex produces code that is both succinct and easy to write.
Database.com Editions 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
You can add Apex to most system events. 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.
3 4
Apex Developer Guide Introducing Apex Apex Developer Guide Introducing Apex
Tip: Note that the semi-colon at the end of the above is not optional. You must end all statements with a semi-colon.
• Locking
For more information about using version settings with managed packages, see About Package Versions in the Salesforce online help. • Data Manipulation Language (DML)
• Transaction Control
• Method Invoking
• Exception Handling
5 6
Apex Developer Guide Introducing Apex Apex Developer Guide Introducing Apex
A block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement Use the following syntax for creating a set:
would be allowed. For example:
Set<datatype> set_name
if (true) { [= new Set<datatype>();] |
System.debug(1); [= new Set<datatype>{value [, value2. . .] };] |
System.debug(2); ;
} else {
System.debug(3); The following example creates a set of String. The values for the set are passed in using the curly braces {}.
System.debug(4);
Set<String> My_String = new Set<String>{'a', 'b', 'c'};
}
In cases where a block consists of only one statement, the curly braces can be left off. For example: For more information, see Sets on page 30.
A map is a collection of key-value pairs. Keys can be any primitive data type. Values can include primitive data types, as well as objects
if (true)
and other collections. Use a map when finding something by key matters. You can have duplicate values in a map, but each key must
System.debug(1);
else
be unique.
System.debug(2); To create a map:
• Use the new keyword
• Use the Map keyword followed by a key-value pair, delimited by a comma and enclosed in <> characters.
Using Collections Use the following syntax for creating a map:
Apex has the following types of collections:
Map<key_datatype, value_datatype> map_name
• Lists (arrays) [=new map<key_datatype, value_datatype>();] |
• Maps [=new map<key_datatype, value_datatype>
{key1_value => value1_value
• Sets
[, key2_value => value2_value. . .]};] |
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 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 first index position in a list is always 0. the map are being passed in between the curly braces {} as the map is being created.
To create a list:
Map<Integer, String> My_Map = new Map<Integer, String>{1 => 'a', 2 => 'b', 3 => 'c'};
• Use the new keyword
For more information, see Maps on page 31.
• Use the List keyword followed by the element type contained within <> characters.
Use the following syntax for creating a list:
Using Branching
List <datatype> list_name
[= new List<datatype>();] |
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
[=new List<datatype>{value [, value2. . .]};] | follows:
; if (Condition){
// Do this if the condition is true
The following example creates a list of Integer, and assigns it to the variable My_List. Remember, because Apex is strongly typed,
} else {
you must declare the data type of My_List as a list of Integer.
// Do this if the condition is not true
List<Integer> My_List = new List<Integer>(); }
For more information, see Lists on page 28. For more information, see Conditional (If-Else) Statements on page 50.
A set is a collection of unique, unordered elements. It can contain primitive data types, such as String, Integer, Date, and so on. It can
also contain more complex data types, such as sObjects. Using Loops
To create a set: While the if statement enables your application to do things based on a condition, loops tell your application to do the same thing
• Use the new keyword again and again based on a condition. Apex supports the following types of loops:
• Use the Set keyword followed by the primitive data type contained within <> characters • Do-while
7 8
Apex Developer Guide Introducing Apex Apex Developer Guide Introducing Apex
Apex
Use Apex if you want to:
• Create Web services.
• Create email services.
• Perform complex validation over multiple objects.
• Create complex business processes that are not supported by workflow.
• Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object).
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an abstract
• Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed, regardless
set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata.
of whether it originates in the user interface, a Visualforce page, or from SOAP API.
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
Lightning Components result. The end user observes no differences in execution time from standard platform requests.
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.
Developing Code in the Cloud
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 The Apex programming language is saved and runs in the cloud—the multitenant platform. Apex is tailored for data access and data
JavaScript. Lightning web components and Aura components can coexist and interoperate on a page.Configure Lightning web manipulation on the platform, and it enables you to add custom business logic to system events. While it provides many benefits for
components and Aura components to work in Lightning App Builder and Experience Builder. Admins and end users don’t know which automating business processes on the platform, it is not a general purpose programming language.
programming model was used to develop the components. To them, they’re simply Lightning components. Apex cannot be used to:
For more information, see the Component Library. • Render elements in the user interface other than error messages
• Change standard functionality—Apex can only prevent the functionality from happening, or add additional functionality
Visualforce • Create temporary files
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing • Spawn threads
the Salesforce user interface. With Visualforce you can:
Tip: All Apex code runs on the Lightning Platform, which is a shared resource used by all other organizations. To guarantee
• Build wizards and other multistep processes. consistent performance and scalability, the execution of Apex is bound by governor limits that ensure no single Apex execution
• Create your own custom flow control through an application. 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.
• Define navigation patterns and data-specific rules for optimal, efficient application interaction.
9 10
Apex Developer Guide Apex Development Process 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 2. Learn more about Apex.
single record at a time. Therefore, you must implement programming patterns that take bulk processing into account. If you don’t, 3. Write your Apex.
you may run into the governor limits.
4. While writing Apex, you should also be writing tests.
5. Optionally deploy your Apex to a sandbox organization and do final unit tests.
SEE ALSO:
6. Deploy your Apex to your Salesforce production organization.
Trigger and Bulk Request Best Practices
In addition to deploying your Apex, once it is written and tested, you can also add your classes and triggers to a AppExchange App
package.
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 Create a Developer or Sandbox Org
learn about testing and deploying Apex code. You can run Apex in a production org, a developer org, or a sandbox org. You can develop Apex in a developer org or a sandbox org,
but not in a production org.
IN THIS SECTION: • Production org—An org that has live users accessing your data
What is the Apex Development Process? • Developer org—An org created with a Developer Edition account
To develop Apex, get a Developer Edition account, write and test your code, then deploy your code. • Sandbox org—An org created on your production org that is a copy of your production org
Create a Developer or Sandbox Org
Note: Apex triggers are available in the Trial Edition of Salesforce. However, they are disabled when you convert to any other
You can run Apex in a production org, a developer org, or a sandbox org. You can develop Apex in a developer org or a sandbox
edition. If your newly signed-up org includes Apex, deploy your code to your org using one of the deployment methods.
org, but not in a production org.
You can't develop Apex in your Salesforce production org. Live users accessing the system while you're developing can destabilize your
Learning Apex
data or corrupt your application. Instead, do all your development work in either a sandbox or a Developer Edition org.
After you have your developer account, there are many resources available to you for learning about Apex
If you aren't already a member of the developer community, go to https://developer.salesforce.com/signup and
Writing Apex Using Development Environments follow the instructions to sign up for a Developer Edition account. A Developer Edition account gives you access to a free Developer
There are several development environments for developing Apex code. The Developer Console and the Salesforce extensions for Edition org. Even if you already have a Professional, Enterprise, Unlimited, or Performance Edition org and a sandbox for creating Apex,
Visual Studio Code allow you to write, test, and debug your Apex code. The code editor in the user interface enables only writing we strongly recommend that you take advantage of the resources available in the developer community.
code and doesn’t support debugging.
Note: You can’t modify Apex using the Salesforce user interface in a Salesforce production org.
Writing Tests
Testing is the key to successful long-term development and is a critical component of the development process. We strongly To create a sandbox org:
recommend that you use a test-driven development process, that is, test development that occurs at the same time as code
1. From Setup, enter Sandboxes in the Quick Find box, then select Sandboxes.
development.
2. Click New Sandbox.
Deploying Apex to a Sandbox Organization
Sandboxes create copies of your Salesforce org in separate environments. Use them for development, testing, and training without 3. Enter a name (10 characters or fewer) and description for the sandbox.
compromising the data and applications in your production org. Sandboxes are isolated from your production org, so operations We recommend that you choose a name that:
that you perform in your sandboxes don’t affect your production org. • Reflects the purpose of this sandbox, such as QA.
Deploying Apex to a Salesforce Production Organization • Has only a few characters, because Salesforce appends the sandbox name to usernames on user records in the sandbox
After you have finished all of your unit tests and verified that your Apex code is executing properly, the final step is deploying Apex environment. Names with fewer characters make sandbox logins easier to type.
to your Salesforce production organization.
4. Select the type of sandbox you want.
Adding Apex Code to a AppExchange App
You can include an Apex class or trigger in an app that you are creating for AppExchange. If you don’t see a sandbox option or need licenses for more, contact Salesforce to order sandboxes for your org.
If you reduce the number of sandboxes you purchase, you are required to match the number of your sandboxes to the number you
purchased. For example, if you have two Full sandboxes but purchased only one, you can’t create a Full sandbox. Instead, convert
What is the Apex Development Process? a Full sandbox to a smaller one, such as a Developer Pro or Developer sandbox, depending on which types you have available.
To develop Apex, get a Developer Edition account, write and test your code, then deploy your code.
5. Select the data to include in your Partial Copy or Full sandbox.
We recommend the following process for developing Apex:
• For a Partial Copy sandbox, click Next, and then select the template you created to specify the data for your sandbox. If you have
1. Obtain a Developer Edition account. not created a template for this Partial Copy sandbox, see Create or Edit Sandbox Templates.
11 12
Apex Developer Guide Apex Development Process Apex Developer Guide Apex Development Process
• For a Full sandbox click Next, and then decide how much data to include. In This Book (Apex Developer's Guide)
– To include template-based data for a Full sandbox, select an existing sandbox template. For more information, see Create Beginning programmers can look at the following:
or Edit Sandbox Templates • Introducing Apex, and in particular:
– To include all data in a Full sandbox, choose whether and how much field tracking history data to include, and whether to
– Documentation Conventions
copy Chatter data. Chatter data includes feeds, messages, and topics and is used in many components that affect your
sandbox copy. Decreasing the amount of data you copy can significantly speed sandbox copy time. – Core Concepts
– Quick Start Tutorial
6. To run scripts after each create and refresh for this sandbox, specify the Apex class you previously created from the SandboxPostCopy
• Classes, Objects, and Interfaces
interface.
• Testing Apex
7. Click Create.
• Execution Governors and Limits
Tip: Try to limit changes in your production org while the sandbox copy proceeds. In addition, advanced programmers can look at:
• Trigger and Bulk Request Best Practices
• Advanced Apex Programming Example
Learning Apex
• Understanding Apex Describe Information
After you have your developer account, there are many resources available to you for learning about Apex
• Asynchronous Execution (@future Annotation)
Apex Trailhead Content
• Batch Apex and Apex Scheduler
Beginning and intermediate programmers
Several Trailhead modules provide tutorials on learning Apex. Use these modules to learn the fundamentals of Apex and how you
can use it on the Lightning Platform. Use Apex to add custom business logic through triggers, unit tests, asynchronous Apex, REST Writing Apex Using Development Environments
Web services, and Visualforce controllers. There are several development environments for developing Apex code. The Developer Console and the Salesforce extensions for Visual
Quick Start: Apex Studio Code allow you to write, test, and debug your Apex code. The code editor in the user interface enables only writing code and
doesn’t support debugging.
Apex Basics & Database
Apex Triggers
Developer Console
Apex Integration Services
The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test
Apex Testing
applications in your Salesforce organization.
Asynchronous Apex
The Developer Console supports these tasks:
Salesforce Developers Apex Page
• Writing code—You can add code using the source code editor. Also, you can browse packages in your organization.
Beginning and advanced programmers
• Compiling code—When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
The Apex page on Salesforce Developers has links to several resources including articles about the Apex programming language.
• Debugging—You can view debug logs and set checkpoints that aid in debugging.
These resources provide a quick introduction to Apex and include best practices for Apex development.
• Testing—You can execute tests of specific test classes or all tests in your organization, and you can view test results. Also, you can
Lightning Platform Code Samples and SDKs
inspect code coverage.
Beginning and advanced programmers
• Checking performance—You can inspect debug logs to locate performance bottlenecks.
Open-source code samples and SDKs, reference code, and best practices can be found at Code samples and SDKs. A library of concise,
• SOQL queries—You can query data in your organization and view the results using the Query Editor.
meaningful examples of Apex code for common use cases, following best practices, can be found at Apex-recipes.
• Color coding and autocomplete—The source code editor uses a color scheme for easier readability of code elements and provides
Development Life Cycle: Enterprise Development on the Lightning Platform
autocompletion for class and method names.
Architects and advanced programmers
The Application Lifecycle and Development Models module on Trailhead helps you learn how to use the application lifecycle and
development models on the Lightning Platform. Salesforce Extensions for Visual Studio Code
Training Courses The Salesforce extension pack for Visual Studio Code includes tools for developing on the Salesforce platform in the lightweight, extensible
Training classes are also available from Salesforce Training & Certification. You can find a complete list of courses at the Training & VS Code editor. These tools provide features for working with development orgs (scratch orgs, sandboxes, and DE orgs), Apex, Aura
Certification site. components, and Visualforce.
See the website for information about installation and usage.
13 14
Apex Developer Guide Apex Development Process Apex Developer Guide Apex Quick Start
Tip: If you want to develop an Apex IDE of your own, the SOAP API includes methods for compiling triggers and classes, and Deploying Apex to a Sandbox Organization
executing test methods, while the Metadata API includes methods for deploying code to production environments. For more
Sandboxes create copies of your Salesforce org in separate environments. Use them for development, testing, and training without
information, see Deploying Apex on page 652 and Using SOAP API to Deploy Apex on page 658.