Data 360 In Apex: You can use Apex with Data 360 objects, with constraints and considerations that are detailed in this topic. Further, you can mock SOQL query responses for Data 360 data model objects (DMOs) in Apex testing by using SOQL stub methods and a test class.
DataWeave in Apex: DataWeave in Apex uses the Mulesoft DataWeave library to read and parse data from one format, transform it, and export it in a different format. You can create DataWeave scripts as metadata and invoke them directly from Apex. Like Apex, DataWeave scripts are run within Salesforce application servers, enforcing the same heap and CPU limits on the executing code.
Implementing DataWeave in Apex: Create DataWeave scripts as metadata and invoke them directly from Apex. Use class methods and exceptions in the DataWeave namespace to load and execute the scripts.
Mock SOQL Tests for Data 360 Data Model Objects: You can mock SOQL query responses for Data 360 data model objects (DMOs) in Apex testing by using the new SOQL stub methods and a new test class. Use static or dynamic SOQL queries against DMOs and return mock records in a testing context.
Territory Management 2.0: With trigger support for the Territory2 and UserTerritory2Association standard objects, you can automate actions and processes related to changes in these territory management records.
Decode the Fact Map: The fact map contains the summary and record-level data values for a report.
Filter Reports: To get specific results on the fly, you can filter reports through the API.
Asynchronous Apex: Apex offers multiple ways for running your Apex code asynchronously. Choose the asynchronous Apex feature that best suits your needs.
Use Batch Apex: To use batch Apex, write an Apex class that implements the Salesforce-provided interface Database.Batchable and then invoke the class programmatically. To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box and then select Apex Jobs.
Firing Platform Events from Batch Apex: Batch Apex classes can fire platform events when encountering an error or exception. Clients listening on an event can obtain actionable information, such as how often the event failed and which records were in scope at the time of failure. Events are also fired for Salesforce Platform internal errors and other uncatchable Apex exceptions such as LimitExceptions, which are caused by reaching governor limits.
Understanding Apex Managed Sharing: Sharing is the act of granting a user or group of users permission to perform a set of actions on a record or set of records. Sharing access can be granted using the Salesforce user interface and Lightning Platform, or programmatically using Apex.
Understanding Sharing: Sharing enables record-level access control for all custom objects, as well as many standard objects (such as Account, Contact, Opportunity and Case). Administrators first set an object’s organization-wide default sharing access level, and then grant additional access based on record ownership, the role hierarchy, sharing rules, and manual sharing. Developers can then use Apex managed sharing to grant additional access programmatically with Apex.
Platform Cache: The Lightning Platform Cache layer provides faster performance and better reliability when caching Salesforce session and org data. Specify what to cache and for how long without using custom objects and settings or overloading a Visualforce view state. Platform Cache improves performance by distributing cache space so that some applications or operations don’t steal capacity from others.
Platform Cache Partitions: Use Platform Cache partitions to improve the performance of your applications. Partitions allow you to distribute cache space in the way that works best for your applications. Caching data to designated partitions ensures that it’s not overwritten by other applications or less-critical data.
Using Certificates with SOAP Services: To support two-way authentication for a callout to a SOAP web service, generate a certificate in Salesforce or import a key pair from a keystore into Salesforce. Then integrate the certificate with your Apex.
Named Credentials as Callout Endpoints: A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. Salesforce manages all authentication for Apex callouts that specify a named credential as the callout endpoint so that your code doesn’t have to. You can also skip remote site settings, which are otherwise required for callouts to external sites, for the site defined in the named credential.
Custom Headers and Bodies of Apex Callouts That Use Named
Credentials: Salesforce generates a standard authorization header for each callout to a named-credential-defined endpoint, but you can disable this option. Your Apex code can also use merge fields to construct each callout’s HTTP header and body.
Generated WSDL2Apex Code: You can generate Apex classes from a WSDL document using the WSDL2Apex tool. The WSDL2Apex tool is open source and available on GitHub.
Test Web Service Callouts: Generated code is saved as an Apex class containing the methods you can invoke for calling the web service. To deploy or package this Apex class and other accompanying code, 75% of the code must have test coverage, including the methods in the generated class. By default, test methods don’t support web service callouts, and tests that perform web service callouts fail. To prevent tests from failing and to increase code coverage, Apex provides the built-in WebServiceMock interface and the Test.setMock method. Use WebServiceMock and Test.setMock to receive fake responses in a test method.
Moderate Chatter Private Messages with Triggers: Write a trigger for ChatterMessage to automate the moderation of private messages in an org or Experience Cloud site. Use triggers to ensure that messages conform to your company’s messaging policies and don’t contain blocklisted words.
Classes, Objects, and Interfaces: Apex classes are modeled on their counterparts in Java. You’ll define, instantiate, and extend classes, and you’ll work with interfaces, Apex class versions, properties, and other related class concepts.
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.
InvocableMethod Annotation: Use the InvocableMethod annotation to identify methods that can be run as invocable actions.
InvocableVariable Annotation: To identify variables used by invocable methods in custom classes, use the InvocableVariable annotation.
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.
SuppressWarnings Annotation: This annotation does nothing in Apex but can be used to provide information to third-party tools.
TearDown Annotation (Developer Preview): Use the TearDown annotation to mark a cleanup method that runs after the test completes, regardless of pass or fail.
Future Annotation: Use the Future annotation to identify methods that run asynchronously. A future method runs when Salesforce has available resources.
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.
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.
Class Methods: Learn how to define Apex methods. Understand the differences between passing method arguments by value and passing method arguments by reference.
Inbound Email: Use Apex to work with email sent to Salesforce.
Using the InboundEmail Object: For every email the Apex email service domain receives, Salesforce creates a separate InboundEmail object that contains the contents and attachments of that email. You can use Apex classes that implement the Messaging.InboundEmailHandler interface to handle an inbound email message. Using the handleInboundEmail method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many functions.
Apex Email Service: You can use email services to process the contents, headers, and attachments of inbound email. For example, you can create an email service that automatically creates contact records based on contact information in messages.
Set an Access Mode for Database Operations: Apex database operations run in user mode by default, which means that they apply the sharing rules, field-level security (FLS), and object permissions of the running user. Database operations only ignore FLS and object permissions if you explicitly set them to run in system mode.
Extending a Class: You can extend a class to provide more specialized behavior.
Enforce Security with Field and SObject Describe Methods: At the most granular level, you can enforce object-level and field-level permissions in your code by explicitly calling the Schema.DescribeSObjectResult and the Schema.DescribeFieldResult methods to check the current user’s access permission levels.
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.
Use 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 are enforced. Use the inherited sharing keyword on a class to run the class in the sharing mode of the calling class. The default sharing mode is with sharing.
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.
Using Regions: A Matcher object finds matches in a subset of its input string called a region. The default region for a Matcher object is always the entirety of the input string. However, you can change the start and end points of a region by using the region method, and you can query the region's end points by using the regionStart and regionEnd methods.
Using Patterns and Matchers: Apex provides patterns and matchers that enable you to search text using regular expressions.
Enforce Object and Field Permissions: Apex generally runs in user context by default, meaning that the current user’s permissions and field-level security (FLS) are enforced during code execution. To ignore the FLS and object permissions of the current user, you must explicitly set a database operation or query to run in system mode. For fine-grained control, you can check the current user’s permissions for an object or a field, and then perform a specific DML operation or a query only if the user has sufficient permissions.
Testing HTTP Callouts: To deploy or package Apex, 75% of your code must have test coverage. By default, test methods don’t support HTTP callouts, so tests that perform callouts fail. Enable HTTP callout testing by instructing Apex to generate mock responses in tests, using Test.setMock.
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.
Class Security: You can specify which users can execute methods in top-level classes or Apex transaction entry points based on their user profile or permission sets. You can only set security on Apex classes, not on triggers.
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.
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.
Enforce Security with the stripInaccessible Method: Use the stripInaccessible method to enforce field-level and object-level data protection by stripping fields and relationship fields from query and subquery results that the user can’t access. The method can also be used to remove inaccessible sObject fields before DML operations to avoid exceptions and to sanitize sObjects that have been deserialized from an untrusted source.
Testing and Code Coverage: The Apex testing framework generates code coverage numbers for your Apex classes and triggers every time you run one or more tests. Code coverage indicates how many executable lines of code in your classes and triggers have been exercised by test methods. Write test methods to test your triggers and classes, and then run those tests to generate code coverage information.
Payment Gateway Adapters: Payment gateway adapters represent the bridge between your payments platform in Salesforce and an external payment gateway.
Alternative Payment Methods: An alternative payment method allows customers to store and represent payment method information not represented by another pre-defined payment method such as CardPaymentMethod or DigitalWallet. Common examples of alternative payment methods include CashOnDeliver, Klarna, and Direct Debit. Alternative payment methods are available in API v51.0 and later.
Building an Asynchronous Gateway Adapter: In an asynchronous payments configuration, the payments platform first sends transaction information to the gateway. The gateway responds with an acknowledgment that it received the transaction, and then the platform creates a pending transaction. The gateway sends a notification, which contains the final transaction status. The platform then updates the transaction’s status accordingly.
Builder Examples for Payment Gateway Adapters: The final sections of a payment gateway adapter should define how the adapter creates requests and responses. The implementation of these classes can vary widely based on your gateway and platform requirements. We’ve provided several generics examples for review.
Idempotency Guidelines: An idempotent payment gateway recognizes duplicate requests, submitted in error or maliciously, and processes them without charging twice. When your gateway supports idempotency, check for duplicates in your adapter before you send a callout.
Process Refund: Process a refund in the payment gateway.
Sample Payment Gateway Implementation for CommercePayments: We’ve created a GitHub repository containing code samples for a sample Payeezy payment gateway implementation with the CommercePayments namespace. Review the sample code if you need help with configuring your payment gateway implementation.
Authorization Reversal Apex Class Implementation: The Authorization Reversal Service uses the AuthorizationReversalRequest and AuthorizationReversalResponse classes to manage the creation and storage of authorization reversal information. Implement these classes in your payment gateway adapter.
Payment Authorization Reversal Service API: An authorization reversal is a transaction that negates an authorization by releasing the hold on funds in a customer’s payment method. Use the authorization reversal service to provide users with the ability to reverse an outstanding payment authorization.
Payment Authorization Reversal Service: An authorization reversal is a transaction that negates an authorization by releasing the hold on funds in a customer’s payment method.
Building a Synchronous Gateway Adapter: In synchronous payment configurations, the Salesforce payment platform sends transaction information to the gateway, and then waits for a gateway response that contains the final transaction status. Salesforce creates a transaction only if the transaction is successful in the gateway.
Tokenization Service Apex Class Implementation: Use the tokenization service to hide sensitive customer payment method data. The Tokenization service uses PaymentMethodTokenizationRequest, PaymentMethodTokenizationResponse, and CardPaymentMethodRequest. Implement these classes in your payment gateway adapter.
Tokenization Service API: The credit card tokenization process replaces sensitive customer information with a one-time algorithmically generated number, called a token, to use during the payment transaction. Salesforce stores the token and then uses that token as a representation of the credit card used for transactions. The token stores information about the credit card without storing sensitive customer data such as credit card numbers. To add tokenization capabilities to your payment services, implement our Tokenization API.
Tokenization Service: The credit card tokenization process replaces sensitive customer information with a one-time algorithmically generated number, called a token, used during the payment transaction. Salesforce stores the token and then uses that token as a representation of the credit card used for transactions. The token lets you store information about the credit card without storing sensitive customer data, such as credit card numbers, in Salesforce.
Using ConnectApi Input and Output Classes: Some classes in the ConnectApi namespace contain static methods that access Connect REST API data. The ConnectApi namespace also contains input classes to pass as parameters and output classes that calls to the static methods return.
Methods Available to Experience Cloud Guest Users: If your Experience Cloud site allows access without logging in, guest users have access to many Apex methods. These methods return information the guest user has access to.
Serializing and Deserializing ConnectApi
Objects: When ConnectApi output objects are serialized into JSON, the structure is similar to the JSON returned from Connect REST API. When ConnectApi input objects are deserialized from JSON, the format is also similar to Connect REST API.
Aggregation for Salesforce Connect Custom Adapters: If you receive a COUNT() query, the selected column has the value QueryAggregation.COUNT in its aggregation property. The selected column is provided in the columnsSelected property on the tableSelection for the DataSource.QueryContext.
Callouts for Salesforce Connect Custom Adapters: Just like any other Apex code, a Salesforce Connect custom adapter can make callouts. If the connection to the external system requires authentication, incorporate the authentication parameters into the callout.
Key Concepts About the Apex Connector Framework: The DataSource namespace provides the classes for the Apex Connector Framework. Use the Apex Connector Framework to develop a custom adapter for Salesforce Connect. Then connect your Salesforce org to any data anywhere via the Salesforce Connect custom adapter.
GitHub Custom Adapter for Salesforce Connect: This example illustrates how to support indirect lookup relationships. An indirect lookup relationship links a child external object to a parent standard or custom object.
GitHub Issues Custom Adapter for Salesforce Connect: This example creates a custom adapter that links GitHub Issues to products in Salesforce using an indirect lookup relationship. An external lookup relationship also links GitHub Issues to the comments on each issue.
Google Drive™ Custom Adapter for Salesforce Connect: This example illustrates how to use callouts and OAuth to connect to an external system, which in this case is the Google Drive™ online storage service. The example also shows how to avoid failing tests from web service callouts by returning mock responses for test methods.
Loopback Custom Adapter for Salesforce Connect: This example illustrates how to handle filtering in queries. For simplicity, this example connects the Salesforce org to itself as the external system.
Stack Overflow Custom Adapter for Salesforce Connect: This example illustrates how to support external lookup relationships and multiple tables. An external lookup relationship links a child standard, custom, or external object to a parent external object. Each table can become an external object in the Salesforce org.
Apex Connector Framework Examples: These examples illustrate how to use the Apex Connector Framework to create custom adapters for Salesforce Connect.
External IDs for Salesforce Connect External Objects: When you access external data with a custom adapter for Salesforce Connect, the values of the External ID standard field on an external object come from the DataSource.Column named ExternalId.
Mock SOQL Tests for External Objects: You can mock SOQL query responses for external objects in Apex testing by using SOQL stub methods and a new test class. Use basic and joined SOQL queries against external objects and return mock records in a testing context.
Writable External Objects: By default, external objects are read only, but you can make them writable. Doing so lets Salesforce users and APIs create, update, and delete data that’s stored outside the org by interacting with external objects within the org. For example, users can see all the orders that reside in an SAP system that are associated with an account in Salesforce. Then, without leaving the Salesforce user interface, they can place a new order or route an existing order. The relevant data is automatically created or updated in the SAP system.
External Change Data Capture Packaging and Testing: You can distribute External Change Data Capture components in managed packages, including a framework for testing your Apex triggers. Special behaviors and limitations apply to packaging and package installation.
Filters in the Apex Connector Framework: The DataSource.QueryContext contains one DataSource.TableSelection. The DataSource.SearchContext can have more than one TableSelection. Each TableSelection has a filter property that represents the WHERE clause in a SOQL or SOSL query.
Paging with the Apex Connector Framework: When displaying a large set of records in the user interface, Salesforce breaks the set into batches and displays one batch. You can then page through those batches. However, custom adapters for Salesforce Connect don’t automatically support paging of any kind. To support paging through external object data that’s obtained by a custom adapter, implement server-driven or client-driven paging.
queryMore with the Apex
Connector Framework: Custom adapters for Salesforce Connect don’t automatically support the queryMore method in API queries. However, your implementation must be able to break up large result sets into batches and iterate over them by using the queryMore method in the SOAP API. The default batch size is 500 records, but the query developer can adjust that value programmatically in the query call.
Support queryMore by Using Server-Driven Paging by Using
Server-Driven Paging: With server-driven paging, the external system controls the paging and ignores any batch boundaries or page sizes that are specified in queries. To enable server-driven paging, declare the QUERY_PAGINATION_SERVER_DRIVEN capability in your DataSource.Provider class.
Get Started with the Apex Connector Framework: To get started with your first custom adapter for Salesforce Connect, create two Apex classes: one that extends the DataSource.Connection class, and one that extends the DataSource.Provider class.
Create a Sample DataSource.Connection Class: First, create a DataSource.Connection class to enable Salesforce to obtain the external system’s schema and to handle queries and searches of the external data.
Salesforce Connect: Apex code can access external object data via any Salesforce Connect adapter. Use the Apex Connector Framework to develop a custom adapter for Salesforce Connect. The custom adapter can retrieve data from external systems and synthesize data locally. Salesforce Connect represents that data in Salesforce external objects, enabling users and the Lightning Platform to seamlessly interact with data that’s stored outside the Salesforce org.
Making an Asynchronous Callout from an Imported WSDL: In addition to HttpRequest-based callouts, asynchronous callouts are supported in Web service calls that are made from WSDL-generated classes. The process of making asynchronous callouts from a WSDL-generated class is similar to the process for using the HttpRequest class.
Chaining Asynchronous Callouts: If the order of the callouts matters, or when a callout is conditional on the response of another callout, you can chain callout requests. Chaining callouts means that the next callout is made only after the response of the previous callout returns. For example, you might need to chain a callout to get warranty extension information after the warranty service response indicates that the warranty expired. You can chain up to three callouts.
Asynchronous Callout Limits: When a continuation is executing, the continuation-specific limits apply. When the continuation returns and the request resumes, a new Apex transaction starts. All Apex and Visualforce limits apply and are reset in the new transaction, including the Apex callout limits.
Making Multiple Asynchronous Callouts: To make multiple callouts to a long-running service simultaneously from a Visualforce page, you can add up to three requests to the Continuation instance. An example of when to make simultaneous callouts is when you’re making independent requests to a service, such as getting inventory statistics for two products.
Make Long-Running Callouts with Continuations: Use asynchronous callouts to make long-running requests from a Visualforce page or a Lightning component to an external Web service and process responses in callback methods.
Process for Using Asynchronous Callouts: To use asynchronous callouts, create a Continuation object in an action method of a controller, and implement a callback method.
Testing Asynchronous Callouts: Write tests to test your controller and meet code coverage requirements for deploying or packaging Apex. Because Apex tests don’t support making callouts, you can simulate callout requests and responses. When you’re simulating a callout, the request doesn’t get sent to the external service, and a mock response is used.
Securing Your Data: You can secure your data by using the methods provided by the Crypto class.
Apex Cursors: Use Apex cursors to break up the processing of a SOQL query result into pieces that can be processed within the bounds of a single transaction. Cursors provide you with the ability to work with large query result sets, while not actually returning the entire result set. You can traverse a query result in parts, with the flexibility to navigate forward and back in the result set. Package developers and advanced developers can use cursors to work with high-volume and high-resource processing jobs. Cursors combined with chained queueable Apex jobs are a powerful alternative to batch Apex and address some of Batch Apex’s limitations.
Large Data Processing with Cursors and Queueable Apex Versus Batch Apex: Apex Cursors combined with chained Queueable Apex jobs are a powerful alternative to Batch Apex for processing large volumes of records. Cursors provide the record-traversal capabilities of Batch Apex, but offer greater flexibility in handling parallel jobs. With Batch Apex, only five active Batch Apex jobs are allowed at one time in your org. Jobs beyond this limit are placed in the Flex Queue, which is limited to 100 additional jobs. In orgs with high volumes of background processing, jobs can accumulate in the Flex Queue and delay critical work.
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.
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.
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.
Debugging Apex: Apex provides debugging support. You can debug your Apex code using the Developer Console and debug logs.
Debug Log Order of Precedence: Which events are logged depends on various factors. These factors include your trace flags, the default logging levels, your API header, user-based system log enablement, and the log levels set by your entry points.
Detecting Duplicate Queueable Jobs: Reduce resource contention and race conditions by enqueuing only a single instance of your async Queueable job based on its signature. Attempting to add more than one Queueable job to the processing queue with the same signature results in a DuplicateMessageException when you try to enqueue subsequent jobs.
Deploying Apex: You can't develop Apex in your Salesforce production org. Your development work is done in a sandbox, in a scratch org, or in a Developer Edition org.
Deploy Apex Using DevOps Center: Salesforce DevOps Center provides an improved experience around change and release management. Build a pipeline when you configure DevOps Center and use the pipeline to promote work items through the release lifecycle from development to production.
Deploy Apex Using Change Sets: Use change sets to deploy Apex classes and triggers between connected organizations, for example, from a sandbox org to your production org.
Deploy Apex Using Metadata API: Use Metadata API to deploy customization information, such as custom object definitions for your org.
Deploy Apex Using Tooling API: Use Tooling API to deploy Apex classes or Apex triggers. Because Tooling API allows you to change just one element within a complex type, it is easy to deploy using Tooling API.
Apex Developer Guide: 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.
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.
sObjects That Can’t Be Used Together in DML Operations: DML operations on certain sObjects, sometimes referred to as setup objects, can’t be mixed with DML on non-setup sObjects in the same transaction. This restriction exists because some sObjects affect the user’s access to records in the org. You must insert or update these types of sObjects in a different transaction to prevent operations from happening with incorrect access-level permissions. For example, you can’t update an account and a user role in a single transaction.
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.
Document Apex Constructs and Features: Apex has unique constructs and platform-specific features that require particular attention in documentation. Use these guidelines to document these elements with ApexDoc.
ApexDoc Examples: See practical examples of ApexDoc comments applied to various Apex constructs.
ApexDoc Comment Structure and Tags: To promote consistency and parsability, ApexDoc comments have a defined structure and syntax. Each ApexDoc comment consists of a main description and a set of block and inline tags that provide information about the documented code element.
Document Your Apex Code: ApexDoc is a standardized comment format that makes it easier for humans, documentation generators, and AI agents to understand your codebase. We recommend using ApexDoc comments to facilitate code collaboration and increase long-term code maintainability. Based on the JavaDoc standard, ApexDoc provides specifications, such as specialized tags and guidelines, that are tailored to Apex and the Salesforce ecosystem.
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.
Exceptions in Apex: Exceptions note errors and other events that disrupt the normal flow of code execution. throw statements are used to generate exceptions, while try, catch, and finally statements are used to gracefully recover from exceptions.
External Services: External Services connect your Salesforce org to a service outside of Salesforce, such as an employee banking service. After you register the external service, you can call it natively in your Apex code. Objects and operations defined in the external service's registered API specification become Apex classes and methods in the ExternalService namespace. The registered service's schema types map to Apex types, and are strongly typed, making the Apex compiler do the heavy lifting for you. For example, you can make a type safe callout to an external service from Apex without needing to use the Http class or perform transforms on JSON strings.
Moderate Feed Items with Triggers: Write a trigger for FeedItem to automate the moderation of posts in an org or Experience Cloud site. Use triggers to ensure that posts conform to your company’s communication policies and don’t contain unwanted words or phrases.
Experience Cloud Sites: Experience Cloud sites are branded spaces for your employees, customers, and partners to connect. You can customize and create sites to meet your business needs, then transition seamlessly between them.
Email: You can use Apex to work with inbound and outbound email.
Outbound Email: Use Apex to work with email sent from Salesforce.
Extend Invocable Action Configuration in Flow Builder: Simplify the configuration of Apex invocable actions in Flow Builder by using the InvocableActionExtension metadata file. Create partial custom property editors for one or more input parameters that don't require updates when you introduce new versions of your action. Define dynamic or static picklists for input parameters and control input parameter display order and grouping. You can also add a custom header to your property editor.
Using Salesforce Features with Apex: Many features of the Salesforce user interface are exposed in Apex so that you can access them programmatically in the Lightning Platform. For example, you can write Apex code to post to a Chatter feed, or use the approval methods to submit and approve process requests.
Suggest Salesforce Knowledge Articles: Provide users with shortcuts to navigate to relevant articles before they perform a search. Call Search.suggest(searchText, objectType, options) to return a list of Salesforce Knowledge articles whose titles match a user’s search query string.
Knowledge Management: Users can write, publish, archive, and manage articles using Apex in addition to the Salesforce user interface.
Salesforce Knowledge: Salesforce Knowledge is a knowledge base where users can easily create and manage content, known as articles, and quickly find and view the articles they need.
Promoted Search Terms: Promoted search terms are useful for promoting a Salesforce Knowledge article that you know is commonly used to resolve a support issue when an end user’s search contains certain keywords. Users can promote an article in search results by associating keywords with the article in Apex (by using the SearchPromotionRule sObject) in addition to the Salesforce user interface.
Salesforce Sites: Salesforce Sites lets you build custom pages and Web applications by inheriting Lightning Platform capabilities including analytics, workflow and approvals, and programmable logic.
Support Classes: Support classes allow you to interact with records commonly used by support centers, such as business hours and cases.
Flows: Flow Builder lets admins build applications, known as flows, that automate a business process. Flows collect data and perform actions in your Salesforce org or an external system.
Chatter Answers and Ideas: In Chatter Answers and Ideas, use zones to organize ideas and answers into groups. Each zone can have its own focus, with unique ideas and answers topics to match that focus.
Formula Evaluation in Apex: Formula evaluation in Apex helps avoid unnecessary DML statements to recalculate formula field values and evaluate dynamic formula expressions. Dynamic formulas in Apex support SObjects and Apex objects as context objects. The context type that corresponds to the Apex class used in the FormulaBuilder.withType() method must be a global, user-defined Apex class. Any fields, properties, or methods that the formula references must also be global.
Execution Governors and Limits: Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces limits so that runaway Apex code or processes don’t monopolize shared resources. If some Apex code exceeds a limit, the associated governor issues a runtime exception that can’t be handled.
Set Up Governor Limit Email Warnings: You can specify users in your organization to receive an email notification when they invoke Apex code that surpasses 50% of allocated governor limits. Only per-request limits are checked for sending email warnings; per-org limits like concurrent long-running requests are not checked. These email notifications do not count against the daily single email limit.
Integration and Apex Utilities: Apex allows you to integrate with external SOAP and REST Web services using callouts. You can use utilities for JSON, XML, data security, and encoding. A general-purpose utility for regular expressions with text strings is also provided.
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.
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.
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.
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.
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.
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.
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.
Learning Apex: After you have your developer account, there are many resources available to you for learning about Apex
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.
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.
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.
Invoking Apex: You can run Apex code with triggers, or asynchronously, or as SOAP or REST web services.
Future Methods: A future method runs asynchronously. You can call a future method to run long-running operations, such as callouts to external web services or any operation that you want to run in its own thread. You can also use future methods to isolate Data Manipulation Language (DML) operations on different sObject types to prevent the mixed DML error. Each future method is queued and runs when system resources become available. That way, the execution of your code doesn’t wait for the completion of a long-running operation. A benefit of future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.
JavaScript Remoting: Use JavaScript remoting in Visualforce to call methods in Apex controllers from JavaScript. Create pages with complex, dynamic behavior that isn’t possible with the standard Visualforce AJAX components.
Roundtrip Serialization and Deserialization: Use the JSON class methods to perform roundtrip serialization and deserialization of your JSON content. These methods enable you to serialize objects into JSON-formatted strings and to deserialize JSON strings back into objects.
JSON Generator: Using the JSONGenerator class methods, you can generate standard JSON-encoded content.
JSON Parsing: Use the JSONParser class methods to parse JSON-encoded content. These methods enable you to parse a JSON-formatted response that's returned from a call to an external service, such as a web service callout.
Elastic Limits for Asynchronous Apex Jobs (Beta): To help avoid disruptions to your workflow, turn on elastic limits for asynchronous Apex jobs (beta). The setting supports throttled processing of asynchronous jobs above the standard rolling 24-hour limit, which prevents execution failures and limit exceptions if your org reaches or exceeds this limit.
Apex Transactions and Governor Limits: Apex Transactions ensure the integrity of data. Apex code runs as part of atomic transactions. Governor execution limits ensure the efficient use of resources on the Lightning Platform multitenant platform.
Running Apex within Governor Execution Limits: When you develop software in a multitenant cloud environment such as the Lightning platform, you don’t have to scale your code, because the Lightning platform does it for you. Because resources are shared in a multitenant platform, the Apex runtime engine enforces some limits to ensure that no one transaction monopolizes shared resources.
Apex Reference: In Summer ’21 and later versions, Apex reference content is moved to a separate guide called the Apex Reference Guide.
Lists of sObjects: Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
Design Managed Apex for Agentforce: As an independent software vendor (ISV) developer, you can build custom agent actions using Apex and distribute them in managed packages. To ensure that subscriber admins can declaratively configure your Apex agent actions and that Agentforce can invoke the actions at run time, follow these requirements and recommendations.
Version Apex Code Behavior: Package developers can use conditional logic in Apex classes and triggers to exhibit different behavior for different versions. With this conditional logic, you can support existing behavior in classes and triggers in previous package versions while evolving the code.
Apex in Managed Packages: Learn how to develop, distribute, and use managed Apex. Apex in managed packages can behave differently than Apex in unmanaged packages or Apex deployed directly to an org. Managed package developers and subscribers must understand these differences so that they can safely evolve their packages and integrations.
Apex Code Items That Aren’t Versioned: Some Apex items in managed packages can’t be versioned. The changes that you make to these items are reflected across all package versions. Additionally, there are limitations to the changes that you can make to some of these items when they are used in Apex code in managed packages.
Testing Versioned Behavior in Apex Code: When you change the behavior in an Apex class or trigger for different package versions, it’s important to test that your code runs as expected in the different package versions. You can write test methods that change the package version context to a different package version by using the System.runAs method. You can only use System.runAs in a test method.
Develop and Distribute Apex for Managed Packages: As an independent software vendor (ISV) or Salesforce partner, you can distribute Apex code to customer orgs by using managed packages. For first-generation managed packages (1GP) and migrated second-generation managed packages (2GP), use versioning to evolve components of your managed package gracefully without breaking existing customer integrations. Understand how global Apex in managed packages behaves and learn how to develop global Apex in managed packages specifically for agents.
Deprecate Managed Apex: Use the @Deprecated annotation to specify Apex identifiers that can subscribers can no longer reference in subsequent releases of the managed package. Deprecation is useful when you’re refactoring code in managed packages as the requirements evolve.
Managed Package Types: Salesforce supports the creation and distribution of Apex through different types of packages. Understand the distinctions between package types, and recognize that Apex behavior can vary across them.
Prevent Field Name Collisions in Managed SOQL Queries: As an independent software vendor (ISV) or managed package developer, prevent duplicate field name errors in dynamic SOQL when a packaged custom field and a subscriber custom field share the same API name. Build a Database.QueryOptions object with explicitNamespace set to true, and pass it as a bind variable in the SOQL SET OPTIONS clause.
Best Practices for Using Global Apex in Managed Packages: As an independent software vendor (ISV) developer, understand when and how to use global Apex in managed packages. Learn design patterns that maximize flexibility and comply with the strict manageability rules applied to global Apex after your managed package’s release. By following these best practices, you can improve the stability and maintainability of your API.
Apex Versioning in Managed Packages: A managed package component can exhibit different behavior in different package versions. By versioning managed Apex, you can add and refine components in the managed package, while maintaining backwards compatibility for existing subscribers.
Safely Upgrade Packages from Developer and Subscriber Perspectives: Learn how to upgrade a managed package safely through this extended example. See the actions that package developers and subscribers can take to ensure a smooth transition and safeguard the backwards compatibility of existing integrations.
Set Package Versions for Apex Classes and Triggers: As a managed package subscriber, you can specify which package version that your managed Apex classes and triggers use. Set the package version in Setup, through metadata deployments, or with API requests.Associate an Apex class or trigger with a specific package version in Setup.Associate an Apex class or trigger with a specific package version by using Metadata API.Specify a managed package version by using the package version header in your API request.
Maps of sObjects: Map keys and values can be of any data type, including sObject types, such as Account.
Metadata: Salesforce uses metadata types and components to represent org configuration and customization. Metadata is used for org settings that admins control, or configuration information applied by installed apps and packages.
JSON Support: JavaScript Object Notation (JSON) support in Apex enables the serialization of Apex objects into JSON format and the deserialization of serialized JSON content.
Visualforce Classes: In addition to giving developers the ability to add business logic to Salesforce system events such as button clicks and related record updates, Apex can also be used to provide custom logic for Visualforce pages through custom Visualforce controllers and controller extensions.
Permission Set Groups: To provide Apex test coverage for permission set groups, write tests using the calculatePermissionSetGroup() method in the System.Test class.
Platform Cache Best Practices: Platform Cache can greatly improve performance in your applications. However, it’s important to follow these guidelines to get the best cache performance. In general, it’s more efficient to cache a few large items than to cache many small items separately. Also be mindful of cache limits to prevent unexpected cache evictions.
Safely Cache Values with the CacheBuilder Interface: A Platform Cache best practice is to ensure that your Apex code handles cache misses by testing for cache requests that return null. You can write this code yourself. Or, you can use the Cache.CacheBuilder interface, which makes it easy to safely store and retrieve values to a session or org cache.
Platform Cache Features: The Platform Cache API lets you store and retrieve data that’s tied to Salesforce sessions or shared across your org. Put, retrieve, or remove cache values by using the Session, Org, SessionPartition, and OrgPartition classes in the Cache namespace. Use the Platform Cache Partition tool in Setup to create or remove org partitions and allocate their cache capacities to balance performance across apps.
Store and Retrieve Values from the Org Cache: Use the Cache.Org and Cache.OrgPartition classes to manage values in the org cache. To manage values in any partition, use the methods in the Cache.Org class. If you’re managing cache values in one partition, use the Cache.OrgPartition methods instead.
Store and Retrieve Values from the Session Cache: Use the Cache.Session and Cache.SessionPartition classes to manage values in the session cache. To manage values in any partition, use the methods in the Cache.Session class. If you’re managing cache values in one partition, use the Cache.SessionPartition methods instead.
Process.Plugin Data Type Conversions: Understand how data types are converted between Apex and the values returned to the Process.Plugin. For example, text data in a flow converts to string data in Apex.
Using the Process.PluginDescribeResult
Class: Use the Process.Plugin interface describe method to dynamically provide both input and output parameters for the flow. This method returns the Process.PluginDescribeResult class.
Using the Process.PluginRequest Class: The Process.PluginRequest class passes input parameters from the class that implements the interface to the flow.
Using the Process.PluginResult Class: The Process.PluginResult class returns output parameters from the class that implements the interface to the flow.
Approval Processing: An approval process automates how records are approved in Salesforce. An approval process specifies each step of approval, including from whom to request approval and what to do at each point of the process.
Sample Process.Plugin Implementation for Lead Conversion: In this example, an Apex class implements the Process.Plugin interface and converts a lead into an account, contact, and optionally, an opportunity. Test methods for the plug-in are also included. This implementation can be called from a flow via a legacy Apex action.
Passing Data to a Flow Using the Process.Plugin
Interface: Process.Plugin is a built-in interface that lets you process data within your org and pass it to a specified flow. The interface exposes Apex as a service, which accepts input values and returns output back to the flow.
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.
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.
Understanding Apex Core Concepts: Apex code typically contains many things that you're familiar with from other programming languages.
Create a Custom Object: In this step, you create a custom object called Book with one custom field called Price.
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.
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.
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.
Queueable Apex: Take control of your asynchronous Apex processes by using the Queueable interface. Salesforce recommends that you use Queueable Apex instead of Apex future methods. Queueables have the same use cases as future methods but offer extra benefits, including job IDs, support for non-primitive types, and job chaining.
Actions: Create quick actions, and add them to your Salesforce Classic home page, to the Chatter tab, to Chatter groups, and to record detail pages. Choose from standard quick actions, such as create and update actions, or create custom actions based on your company’s needs.
Apex Release Notes: Use the Salesforce Release Notes to learn about the most recent updates and changes to Apex.
Exposing Apex Classes as REST Web Services: You can expose your Apex classes and methods so that external applications can access your code and your application through the REST architecture.
Apex REST Basic Code Sample: This sample shows how to implement a simple REST API in Apex with three HTTP request methods to delete, retrieve, and update a record.
Exposing Data with Apex REST Web Service Methods: Custom Apex REST web service methods run in user mode by default. In user mode, the current user’s object permissions, field-level security, and sharing rules are enforced.
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.
Salesforce Files: Use Apex to customize the behavior of Salesforce Files.
Customize File Downloads: You can customize the behavior of files when users attempt to download them using an Apex callback. ContentVersion supports modified file behavior, such as antivirus scanning and information rights management (IRM), after the download operation. File download customization is available in API version 39.0 and later.
Custom File Download Examples: You can use Apex to customize the behavior of files upon attempted download. These examples assume that only one file is being downloaded. File download customization is available in API version 39.0 and later.
Apex Scheduler: Use the Apex Scheduler to delay execution so that you can run Apex classes at a specified time. This is ideal for daily or weekly maintenance tasks using Batch Apex.
Apex Security and Sharing Model: The Apex security model includes record-level, field-level, and object-level security mechanisms. You can control record-level security modes by using the with sharing, without sharing, and inherited sharing keywords on classes. Apex runs in user mode by default, which means that user permissions on objects and field-level security are respected. A user cannot run code that tries to access fields or objects that are hidden from the user. Other security mechanisms include the Security.stripInaccessible() method, and Field and SObject describe methods.
Enforce Sharing Rules: In Apex, sharing rules are always enforced by default. Use the with sharing, without sharing, and inherited sharing keywords to control record-level security. If you don't want sharing rules to be enforced, then you must declare a class with the without sharing keyword.
Sets of Objects: Sets can contain sObjects among other types of elements.
Rewrite URLs for Salesforce Sites: Sites provides built-in logic that helps you display user-friendly URLs and links to site visitors. Create rules to rewrite URL requests typed into the address bar, launched from bookmarks, or linked from external websites. You can also create rules to rewrite the URLs for links within site pages. URL rewriting not only makes URLs more descriptive and intuitive for users, it allows search engines to better index your site pages.
Testing Apex: Apex provides a testing framework that allows you to write unit tests, run your tests, check test results, and have code coverage results.
Isolation of Test Data from Organization Data in Unit Tests: By default, Apex test methods (API version 24.0 and later) can’t access pre-existing org data such as standard objects, custom objects, and custom settings data. They can only access data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in your tests.
Apex Integration Tests (Developer Preview): Use Apex integration tests to write end-to-end tests that exercise real interactions between your Salesforce org and external services, including Agentforce and Data 360, as well as HTTP endpoints. Unlike standard Apex unit tests, integration tests relax callout restrictions and transaction rollback semantics, so your tests can make real service calls, commit data mid-transaction, and make assertions on expected outcomes. As a developer preview feature, integration tests are available only in scratch orgs. You can’t run them in production orgs or during metadata deployments.
Loading Test Data: Using the Test.loadData method, you can populate data in your test methods without having to write many lines of code.
Using the isTest(SeeAllData=True) Annotation: Annotate your test class or test method with IsTest(SeeAllData=true) to open up data access to records in your organization. The IsTest(SeeAllData=true) annotation applies to data queries but doesn't apply to record creation or changes, including deletions. New and changed records are still rolled back in Apex tests even when using the annotation.
Build a Mocking Framework with the Stub API: Apex provides a stub API for implementing a mocking framework. A mocking framework has many benefits. It can streamline and improve testing and help you create faster, more reliable tests. You can use it to test classes in isolation, which is important for unit testing. Building your mocking framework with the stub API can also be beneficial because stub objects are generated at runtime. Because these objects are generated dynamically, you don’t have to package and deploy test classes. You can build your own mocking framework, or you can use one built by someone else.
Using Test Setup Methods: Use test setup methods (methods that are annotated with @TestSetup) to create test records once and then access them in every test method in the test class. Test setup methods can be time-saving when you need to create reference or prerequisite data for all test methods, or a common set of records that all test methods operate on.
Using the runAs Method: Generally, all Apex code runs in user mode, where the object-level and field-level permissions of the current user are enforced. With the System method runAs, you can write test methods that change the user context to an existing user or a new user. Then that user’s sharing rules and object-level and field-level permissions are enforced.
Run Unit Test Methods: To verify the functionality of your Apex code, execute unit tests. You can run Apex test methods in the Developer Console, in Setup, in the Salesforce extensions for Visual Studio Code, or using the API.
Apex Transactions: An Apex transaction represents a set of operations that are executed as a single unit. All DML operations in a transaction must complete successfully. If an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database. The boundary of a transaction can be a trigger, a class method, an anonymous block of code, a Visualforce page, or a custom Web service method.
Transaction Finalizers: The Transaction Finalizers feature enables you to attach actions, using the System.Finalizer interface, to asynchronous Apex jobs that use the Queueable framework. A specific use case is to design recovery actions when a Queueable job fails.
Triggers: Apex can be invoked by using triggers. Apex triggers enable you to perform custom actions before or after changes to Salesforce records, such as insertions, updates, or deletions.
Trigger Context Variables: All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.
Trigger Considerations for Knowledge Articles: You can write triggers for KnowledgeArticleVersion objects. Learn when you can use triggers, and which actions don’t fire triggers, like archiving articles.
Triggers and Order of Execution: When you save a record with an insert, update, or upsert statement, Salesforce performs a sequence of events in a certain order.
Exposing Apex Methods as SOAP Web Services: You can expose your Apex methods as SOAP web services so that external applications can access your code and your application.
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.
XML Support: Apex provides utility classes that enable the creation and parsing of XML content using streams and the DOM.
ZIP Support: Take advantage of a native Apex Zip library to create and extract ZIP archive files by using the class methods in the Compression namespace.
Authentication: Salesforce provides various ways to authenticate users. Build a combination of authentication methods to fit the needs of your org and your users’ use patterns.
Connect in Apex: Use Connect in Apex to develop custom experiences in Salesforce. Connect in Apex provides programmatic access to B2B Commerce, CMS managed content, Experience Cloud sites, topics, and more. Create Apex pages that display Chatter feeds, post feed items with mentions and topics, and update user and group photos. Create triggers that update Chatter feeds.
Get Site-Specific Feed Elements from a Feed: Call a method to display a user profile feed that contains only feed elements that are scoped to a specific Experience Cloud site.
Connect in Apex Features: This topic describes which classes and methods to use to work with common Connect in Apex features.
Working with Action Links: An action link is a button on a feed element. Clicking an action link can take a user to a Web page, initiate a file download, or invoke an API call to Salesforce or to an external server. An action link includes a URL and an HTTP method, and can include a request body and header information, such as an OAuth token for authentication. Use action links to integrate Salesforce and third-party services into the feed so that users can drive productivity and accelerate innovation.
Action Links Use Case: Use action links to integrate Salesforce and third-party services with a feed. An action link can make an HTTP request to a Salesforce or third-party API. An action link can also download a file or open a web page. This topic contains an example use case.
Working with Feeds and Feed Elements: The Chatter feed is a container of feed elements. The abstract class ConnectApi.FeedElement is a parent class to the ConnectApi.FeedItem class, representing feed posts, and the ConnectApi.GenericFeedElement class, representing bundles and recommendations in the feed.
Wildcards: Use wildcard characters to match text patterns in Connect REST API and Connect in Apex searches.
Null Coalescing Operator: The ?? operator returns its right-hand side operand when its left-hand side operand is null. Similar to the safe navigation operator (?.), the null coalescing operator (??) replaces verbose and explicit checks for null references in code.
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.
Working with Very Large SOQL Queries: Your SOQL query sometimes returns so many sObjects that the limit on heap size is exceeded and an error occurs. To resolve, use a SOQL query for loop instead, since it can process multiple batches of records by using internal calls to query and queryMore.
Working with SOQL Aggregate Functions: Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query.
Working with Polymorphic Relationships in SOQL Queries: A polymorphic relationship is a relationship between objects where a referenced object can be one of several different types. For example, the Who relationship field of a Task can be a Contact or a Lead.
sObject Types: An sObject variable represents a row of data and can only be declared in Apex using SOAP API name of the object.
Working with sObjects: In this developer guide, the term sObject, when used as a placeholder value, refers to any object that can be stored in the Lightning platform database.
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.
Assignment Statements: An assignment statement is any statement that places a value into a variable.
Collections: Collections in Apex can be lists, sets, or maps.
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.
List Sorting: You can sort list elements and the sort order depends on the data type of the elements.
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.
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.
Constants: Apex constants are variables whose values don’t change after being initialized once. Constants can be defined using the final keyword.
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.
Data Types: In Apex, all variables and expressions have a data type, such as sObject, primitive, or enum.
Data Types and Variables: Apex uses data types, variables, and related language constructs such as enums, constants, expressions, operators, and assignment statements.
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.
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.
Setting DML Options: You can specify DML options for insert and update operations by setting the desired options in the Database.DMLOptions object. You can set Database.DMLOptions for the operation by calling the setOptions method on the sObject, or by passing it as a parameter to the Database.insert and Database.update methods.
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.
Merging Records: When you have duplicate lead, contact, case, or account records in the database, cleaning up your data and consolidating the records is a good idea. You can merge up to three records of the same sObject type. The merge operation merges the duplicate records into the main record, deletes the duplicate records, and reparents any related records.
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.
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.
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.
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.
Expressions and Operators: An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value.
Comments: Both single and multiline comments are supported in Apex code.
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.
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.
Loops: Apex supports five types of procedural loops.
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.
Primitive Data Types: Apex uses the same primitive data types as SOAP API, except for higher-precision Decimal type in certain cases.
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.
Switch Statements: Apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly.
Transaction Control: Read about transaction requests, generating and releasing savepoints, rolling back transactions, and more.
Variables: Local variables are declared with Java-style syntax.
Data Access Control: The Salesforce Platform makes extensive use of data sharing rules. Each object has permissions and can have sharing settings that users can read, create, edit, and delete. These settings are enforced when using all standard controllers.
Unescaped Output and Formulas in Visualforce Pages: When using components that have set the escape attribute to false, or when including formulas outside of a Visualforce component, output is unfiltered and must be validated for security. This is especially important when using formula expressions.
OAuth 2.0 Token Exchange Handler Examples: Sometimes you want to integrate Salesforce into a complex system where you have a primary app, a central identity provider, and multiple other apps and microservices. In this model, users log in to the primary app via the identity provider and access data provided by the other apps and microservices. To fit Salesforce into this model as one of the apps providing data, use the OAuth 2.0 token exchange flow, which implements an Apex token exchange handler.
Apex Versioned Behavior Changes: This document includes major Apex behavior changes across API versions, organized by version number for easy lookup. It isn’t an exhaustive list of all versioned Apex behavior. For example, this compilation excludes versioned changes to Connect in Apex and classes in the ConnectApi namespace.