Apex Tutorial in Tutorial Points
Apex Tutorial in Tutorial Points
i
Apex
Audience
This tutorial is targeted for Salesforce programmers beginning to learn Apex. This will
bring you to an Intermediate level of expertise in Apex programming covering all the
important aspects of Apex with complete hands-on code experience.
Prerequisites
Basic knowledge of Salesforce platform and development is needed. Apex is a
programming language which has to be used with Salesforce. This tutorial assumes that
you already have set up the Salesforce instance which will be used to do our Apex
programming.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Apex
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Flow of Actions........................................................................................................................................ 3
ii
Apex
Lists ....................................................................................................................................................... 50
Sets ....................................................................................................................................................... 52
Maps ..................................................................................................................................................... 53
iii
Apex
Overloading Constructors...................................................................................................................... 62
DML Statements.................................................................................................................................... 70
iv
Apex
SOSL ...................................................................................................................................................... 80
SOQL ..................................................................................................................................................... 81
v
Apex
Finish................................................................................................................................................... 109
Scheduling the Apex Batch Job using Apex Detail Page ....................................................................... 112
Scheduling the Apex Batch Job using Schedulable Interface ................................................................ 113
vi
Apex
1. APEX – OVERVIEW
What is Apex?
Apex is a proprietary language developed by the Salesforce.com. As per the official definition,
Apex is a strongly typed, object-oriented programming language that allows developers to
execute the flow and transaction control statements on the Force.com platform server in
conjunction with calls to the Force.com API.
It has a Java-like syntax and acts like database stored procedures. It enables the 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. Apex is included in Performance Edition, Unlimited Edition, Enterprise Edition, and
Developer Edition.
Integrated
Apex has built in support for DML operations like INSERT, UPDATE, DELETE and also DML
Exception handling. It has support for inline SOQL and SOSL query handling which returns
the set of sObject records. We will study the sObject, SOQL, SOSL in detail in future chapters.
7
Apex
Apex is easy to use as it uses the syntax like Java. For example, variable declaration, loop
syntax and conditional statements.
8
Apex
Strongly Typed
Apex is a strongly typed language. It uses direct reference to schema objects like sObject and
any invalid reference quickly fails if it is deleted or if is of wrong data type.
Multitenant Environment
Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed
to guard closely against runaway code, preventing it from monopolizing shared resources.
Any code that violates limits fails with easy-to-understand error messages.
Upgrades Automatically
Apex is upgraded as part of Salesforce releases. We don't have to upgrade it manually.
Easy Testing
Apex provides built-in support for unit test creation and execution, including test results that
indicate how much code is covered, and which parts of your code can be more efficient.
Apex Applications
We can use Apex when we want to:
Perform complex validation over multiple objects at the same time and also custom
validation implementation.
Create complex business processes that are not supported by existing workflow
functionality or flows.
Create custom transactional logic (logic that occurs over the entire transaction, not
just with a single record or object) like using the Database methods for updating the
records.
Perform some logic when a record is modified or modify the related object's record
when there is some event which has caused the trigger to fire.
9
Apex
Flow of Actions
There are two sequence of actions when the developer saves the code and when an end user
performs some action which invokes the Apex code as shown below:
Developer Action
When a developer writes and saves Apex code to the platform, the platform application server
first compiles the code into a set of instructions that can be understood by the Apex runtime
interpreter, and then saves those instructions as metadata.
Since Apex is the proprietary language of Salesforce.com, it does not support some features
which a general programming language does. Following are a few features which Apex does
not support:
You cannot change the standard SFDC provided functionality and also it is not possible
to prevent the standard functionality execution.
10
Apex
Variable Declaration
As strongly typed language, you must declare every variable with data type in Apex. As seen
in the code below (screenshot below), lstAcc is declared with data type as List of Accounts.
SOQL Query
This will be used to fetch the data from Salesforce database. The query shown in screenshot
below is fetching data from Account object.
Loop Statement
This loop statement is used for iterating over a list or iterating over a piece of code for a
specified number of times. In the code shown in the screenshot below, iteration will be same
as the number of records we have.
DML Statement
Performs the records insert, update, upsert, delete operation on the records in database. For
example, the code given below helps in updating Accounts with new field value.
Following is an example of how an Apex code snippet will look like. We are going to study all
these Apex programming concepts further in this tutorial.
11
Apex
12
Apex
2. APEX – ENVIRONMENT
In this chapter, we will understand the environment for our Salesforce Apex development. It
is assumed that you already have a Salesforce edition set up for doing Apex development.
You can develop the Apex code in either Sandbox or Developer edition of Salesforce. A
Sandbox organization is a copy of your organization in which you can write code and test it
without taking the risk of data modification or disturbing the normal functionality. As per the
standard industrial practice, you have to develop the code in Sandbox and then deploy it to
the Production environment.
For this tutorial, we will be using the Developer edition of Salesforce. In the Developer edition,
you will not have the option of creating a Sandbox organization. The Sandbox features are
available in other editions of Salesforce.
Force.com IDE
Note: We will be utilizing the Developer Console throughout our tutorial for code execution
as it is simple and user friendly for learning.
13
Apex
Step2: Click on "Developer Console" and a window will appear as in the following screenshot.
Following are a few operations that can be performed using the Developer Console.
Writing and compiling code - You can write the code using the source code editor.
When you save a trigger or class, the code is automatically compiled. Any compilation
errors will be reported.
Debugging - You can view debug logs and set checkpoints that aid in debugging.
Testing - You can execute tests of specific test classes or all classes in your
organization, and you can view test results. Also, you can inspect code coverage.
14
Apex
SOQL queries - You can query data in your organization and view the results using
the Query Editor.
Color coding and autocomplete - The source code editor uses a color scheme for
easier readability of code elements and provides auto completion for class and method
names.
Step 1: Login to the Salesforce.com using login.salesforce.com. Copy the code snippets
mentioned in the tutorial. For now, we will use the following sample code:
Step 2: To open the Developer Console, click on Name -> Developer Console and then click
on Execute Anonymous as shown below.
15
Apex
Step 3: In this step, a window will appear and you can paste the code there.
16
Apex
Step 4: When we click on Execute, the debug logs will open. Once the log appears in window
as shown below, then click on the log record:
Then type 'USER' in the window as shown below and the output statement will appear in the
debug window. This 'USER' statement is used for filtering the output.
So basically, you will be following all the above mentioned steps to execute any code snippet
in this tutorial.
17
Apex
3. APEX – EXAMPLE
For executing the code in this tutorial, you will need to have two objects created: Customer
and Invoice objects. If you already know how to create these objects in Salesforce, you can
skip the steps given below. Else, you can follow the step by step guide below.
Step 1: Go to Setup and then search for 'Object' as shown below. Then click on the Objects
link as shown below:
18
Apex
Step 2: Once the object page is opened, then click on the 'Create New Object' button as
shown below:
Step 3: After clicking on button, the new object creation page will appear and then enter all
the object details as entered below. Object name should be Customer. You just have to enter
the information in the field as shown in the screenshot below and keep other default things
as it is.
19
Apex
By following the above steps, we have successfully created the Customer object.
Step 1: We will be creating a field named as 'Active' of data type as Checkbox. Go to Setup
and click on it.
20
Apex
Step 4: Once you have clicked on the Customer object link and the object detail page appears,
click on the New button:
21
Apex
Step 5: Now, select the data type as Checkbox and click Next:
22
Apex
By following the above steps, our custom field 'Active' is created. You have to follow all the
above custom field creation steps for the remaining fields. This is the final view of customer
object once all the fields are created:
23
Apex
Step 2: Once the object page is opened, then click on the 'Create New Object' button as
shown below:
Step 3: After clicking on the button, the new object creation page will appear as shown in
the screenshot below. You need to enter the details here. The object name should be Invoice.
This is similar to how we created the Customer object earlier in this tutorial.
24
Apex
25
Apex
26