Apex and Triggers
Apex and Triggers
Definitions
Programming Elements
Concepts
Encapsulation
Abstraction
the Programming
Polymorphism
Keywords: override
Inheritance
same object.
5. Static variables and methods, we can directly call with class name (we
List Set
Contains method is not available in List. Contains method is available for Set
No limit for the size of a list. It only depends on the heap size which is 6 MB
1. Insert
2. Update
3. Delete
4. Undelete
8.What is SOQL?
1. SOQL: Salesforce Object Query Language
3. We can write query on one object while querying on those objects we can
fetch the child object info. or parent object info. (We cannot capture un related
objects info.)
9.What is SOSL?
2. SOSL Purpose: We can search for a value in multiple objects (no need of
any relationship).
or after data manipulation language (DML) events occur. Apex triggers enable
Before Mode: Before the record is saving into the database, it will fire.
After Mode: After the record is saved into the database (doesn't commit at this
Before After
before
after insert
insert
before after
update update
before
after delete
delete
after
-
undelete
2. trigger.oldMap (stores history (old versions) of the records along with id.)
events?
before insert ✘ ✘ ✔ ✘
after insert ✘ ✘ ✔ ✔
before ✔ ✔ ✔ ✔
update
after update ✔ ✔ ✔ ✔
before
✔ ✔ ✘ ✘
delete
after delete ✔ ✔ ✘ ✘
after
✘ ✘ ✔ ✔
undelete
triggers?
Before Triggers
2. If you are updating any field on the same object on which you are writing
the trigger and no need to explicitly include the DML statements (already due to
DML operation only trigger fire and it is still in progress at this point of time.)
After Triggers
1. If you are dealing with relationship records and if you need record id in
these situations we should use after trigger (in before insert record doesn't
3.
4. execution?
Using static boolean variable in an apex class (we should not keep static boolean
2. It will replace all the old field values with new field values.
3. If the request is coming form UI all the system validations will execute -
• DataType
• Length
• Required
• unique
4. before triggers
5. Custom Validations and again system validation rules will fire (pageLayot
6. record will be saved into the database but doesn't not commit.
7. after triggers.
8. assignment rules.
9. auto-responsive rules.
11. In case of Workflow Rule Field updates again before triggers and after
triggers fire one more time. System validation rules for duplicate check.
at a later time.
background" without the user having to wait for the task to finish.
7.
Batch Run large jobs that would exceed normal Data cleansing or archiving of
Scheduled
Schedule Apex to run at a specified time. Daily or weekly tasks.
Apex
8.
2 @future
5 }
6}
• Future methods must be static methods, and can only return a void type.
• A common pattern is to pass the method a list of record IDs that you want
to process asynchronously.
2 @future
6 // Process records
7 }
8}
Future method callouts using @future(callout=true)
To allow callout from the future method annotation needs an extra parameter
2 @future(callout=true)
5 }
6}
i.e., here, data would be divided into small batches of records, and then it would be
process bulk data or records together and have a greater governor limit than the
synchronous code.
• Until a batch is not successfully executed, Batch Apex won’t execute the
following batches.
Apex classes.
• The interface can be scheduled to run batches at different periods
• Batch jobs are invoked programmatically during the runtime and can be
operated on any size of records, with a maximum of 200 records per batch. You
can break down a larger record data into 200 records per batch to execute it
better.
There are various reasons why Batch Apex is better than normal Apex.
• SOQL queries: Normal Apex uses 100 records per cycle to execute SOQL
queries. Whereas, Batch Apex does the same in 200 records per cycle.
• Heap size: Normal Apex has a heap size of 6 MB; whereas, Batch Apex has
• Errors: When executing bulk records, Normal Apex classes are more
Get familiar with the top Salesforce Interview Questions to get a head
data on which the batch job will be operating. It breaks the data or record into
batches. In some cases, the ‘QueryLocator’ method is used to operate with the
simple SOQL query to generate the scope of objects inside a batch job.
• Syntax:
• Execute: This method executes after the Start method, and it does the
• Syntax:
• Finish: This method will be called at last. Since this method is called in the
email. When this process is called all batches are already executed.
• Syntax:
You can schedule your Batch Apex class using the developer console or
time. However, you have to write the Apex Class file in order to execute
the batchable interface. You can also chain the two or more apex Batch
Classes together to execute one job after another. Moreover, you can
split an Apex record into batches and schedule the groups of them to
Now let’s look at the main differences between Future and queueable apex
same apex class to write the future interface. Syntax: public class CLASS_NAME
We cannot monitor the jobs We can monitor the jobs based on the job Id.
we cannot call a future from another We can chain the Queueable jobs and the
future or batch apex. The limit on future stack depth in developer org is 5 and in
method for single apex invocation is 50. enterprise edition you can chain 50 jobs.
Future method supports only primitive Queueable supports both primitive and non-
as Queueable apex class. This interface enables you to add jobs to the queue
Apex code compared to using future methods. The interface has only one
record. You can use this ID to identify your job and monitor its progress,
either through the Salesforce user interface in the Apex Jobs page, or
Chaining jobs: You can chain one job to another job by starting a second job
from a running job. Chaining jobs is useful if you need to do some sequential
processing.
Example:
6 }
7}
The execution of a queued job counts once against the shared limit for asynchronous
transaction.
• No limit is enforced on the depth of chained jobs, which means that you
• You can add only one job from an executing job with System.enqueueJob,
means that only child job can exist for parent queueable job.--->For Developer Edition
and Trial organizations, the maximum stack depth for chained jobs is 5.
the Schedulable interface for the class, then specify the schedule using either the
Schedule Apex page in the Salesforce user interface, or the System.schedule method.
Important
Salesforce schedules the class for execution at the specified time. Actual
You can only have 100 scheduled Apex jobs at one time. You can evaluate your
current count by viewing the Scheduled Jobs page in Salesforce and creating a
custom view with a type filter equal to “Scheduled Apex”. You can also
Use extreme care if you’re planning to schedule a class from a trigger. You must
be able to guarantee that the trigger won’t add more scheduled classes than the
limit. In particular, consider API bulk updates, import wizards, mass record
changes through the user interface, and all cases where more than one record
If there are one or more active scheduled jobs for an Apex class, you cannot
update the class or any classes referenced by this class through the Salesforce
user interface. However, you can enable deployments to update the class with
active scheduled jobs by using the Metadata API (for example, when using the
Salesforce extensions for Visual Studio Code). See “Deployment Connections for
To schedule an Apex class to run at regular intervals, first write an Apex class
The scheduler runs as system—all classes are executed, whether or not the user
user interface, from Setup, enter Scheduled Jobs in the Quick Find box, then
implemented, execute.
Tip
called mergeNumbers:
To implement the above class, execute this example in the Developer Console.
You can also use the Schedulable interface with batch Apex classes. The
following example implements the Schedulable interface for a batch Apex class
called batchable:
database.executebatch(b);
Use the SchedulableContext object to keep track of the scheduled job once it's
the CronTrigger object associated with this scheduled job as a string. You can
To stop execution of a job that was scheduled, use the System.abortJob method
Tracking the Progress of a Scheduled Job Using Queries After the Apex job has
been scheduled, you can obtain more information about it by running a SOQL
query on CronTrigger and retrieving some fields, such as the number of times the
job has run, and the date and time when the job is scheduled to run again, as
Id = :jobID];
The previous example assumes you have a jobID variable holding the ID of the
job. The System.schedule method returns the job ID. If you’re performing this
query inside the execute method of your schedulable class, you can obtain the ID
variable. Assuming this variable name is sc, the modified example becomes:
CronTrigger ct =
You can also get the job’s name and the job’s type from the CronJobDetail record
example retrieves the most recent CronTrigger record with the job name and
CronTrigger job =
Alternatively, you can query CronJobDetail directly to get the job’s name and
type. This next example gets the job’s name and type for the CronTrigger record
CronJobDetail ctd =
To obtain the total count of all Apex scheduled jobs, excluding all other scheduled
job types, perform the following query. Note the value '7' is specified for the job