0% found this document useful (0 votes)
33 views21 pages

Apex and Triggers

The document provides a comprehensive overview of Apex and triggers in Salesforce, covering key OOP concepts, differences between static and non-static elements, types of collections, and DML statements. It explains SOQL and SOSL, the differences between various trigger events, context variables, and the order of execution in Salesforce. Additionally, it discusses asynchronous Apex, including future methods, batch Apex, and queueable Apex, highlighting their functionalities and use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views21 pages

Apex and Triggers

The document provides a comprehensive overview of Apex and triggers in Salesforce, covering key OOP concepts, differences between static and non-static elements, types of collections, and DML statements. It explains SOQL and SOSL, the differences between various trigger events, context variables, and the order of execution in Salesforce. Additionally, it discusses asynchronous Apex, including future methods, batch Apex, and queueable Apex, highlighting their functionalities and use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

APEX AND TRIGGERS: -

1.What are the Oop's Concepts?

Definitions

Programming Elements

-Variables and methods come under Programming Elements

Concepts

Encapsulation

Binding the Programming Elements into a single unit.

Keywords: class and interface

Abstraction

the Programming

Keywords: private, public, protected and global.

Polymorphism

Different behaviour of the Programming Elements

Keywords: override

Inheritance

Reusing one encapsulation from another encapsulation

Keywords: extends and implements

Apex follows above concepts hence we call apex as a based language.

Apex is case-insensitive Language.


2.What is the difference between non-static and static?

1. By default, all the variables and methods are non-static.

2. Scope of the non-static variables or methods is within the scope of the

same object.

3. We can declare variables and methods as static by using static keyword.

4. Scope of the static variables and methods is throughout the transaction.

5. Static variables and methods, we can directly call with class name (we

cannot access static variables and methods with object name).

3.What are the types of Collections available in Apex?

1. List (ordered and allow duplicates)

2. Set (unordered and won't allow duplicates)

3. Map (Key and value pair)

4.What is the difference between List and Set?

List Set

List is Ordered. Set is unordered.

List allows duplicates. Set doesn't allow duplicates.

Set elements cannot be accessed


We can access list elements with index.
with index.

We can sort list elements with sort method


sort method is not available for Set.
(default sorting order is ascending).

Contains method is not available in List. Contains method is available for Set

to search for a particular element in


the set.

We can process records which are stored in list


We cannot process records which are
using DML statements (insert, update, delete
stored in set using DML statements.
and undelete).

5.What is the maximum size of the list?

No limit for the size of a list. It only depends on the heap size which is 6 MB

(Synchronous) and 12 MB (Asynchronous).

6.What are the map methods available in Apex?

1. keyset (): To fetch only keys from the map.

2. values (): To fetch only values from the map.

3. contains Key(value): To search a key from the map.

4. get(key): By supplying the key we can fetch the value.

5. put(key, value): To add key and value in a map.

7.What are the DML statements available in Apex?

1. Insert

2. Update

3. Delete

4. Undelete

5. Upsert (Combination of insert and update)

6. Merge (Combination of update and delete)

8.What is SOQL?
1. SOQL: Salesforce Object Query Language

2. SOQL Purpose: To fetch info. from an object and related objects.

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.)

4. SOQL queries per transaction: 100.

5. SOQL query rows returned: 50000.

9.What is SOSL?

1. SOSL: Salesforce Object Search Language

2. SOSL Purpose: We can search for a value in multiple objects (no need of

any relationship).

3. Results of SOSL query can be stored in List of List.

4. SOSL queries per transaction: 20.

5. SOSL query rows returned: 2000.

10.Difference between insert/update and Database. Insert/ Database.update?

insert/update Database. Insert/Database.update

Assume that you are inserting


Assume that you are inserting 100 records. If any
100 records. If any one of the
one of the record fail due to error then it will perform
records fail due to error then
partial operation (valid records will be
entire operation will fail. None of
inserted/updated) if we use Database.
the records will be saved into
Insert(list,false)/ Database. Update(list,false).
the database.

with insert/update if we use try- with Database. Insert/Database.update we can


catch then we can capture only
capture all the errors by saving result
one error which will cause to
in Database.saveResult[].
stop the operation.

11.What is Triggers in Salesforce? A trigger is an Apex script that executes before

or after data manipulation language (DML) events occur. Apex triggers enable

you to perform custom actions before or after events to record in Salesforce,

such as insertions, updates, or deletions.

12.What are the trigger events?

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

point of time), it will fire.

Before After

before
after insert
insert

before after

update update

before
after delete
delete

after
-
undelete

Note: before undelete event is not available.


1. 13.What are the trigger context variables?

To capture the runtime information we use trigger context variables.

Below context variables will return either true or false.

1. Trigger.isBefore (returns true if the trigger context is Before Mode)

2. Trigger.isAfter (returns true if the trigger context is After Mode)

3. Trigger.isInsert (returns true if the trigger context is Insert)

4. Trigger.isUpdate (returns true if the trigger context is Update)

5. Trigger.isDelete (returns true if the trigger context is Delete)

6. Trigger.isUndelete (returns true if the trigger context is Undelete)

7. Trigger.isExecuting (returns true if the apex class method is getting call

from Apex Trigger)

Below context variables will store records at runtime.

1. trigger.old (stores history (old versions) of the records.)

2. trigger.oldMap (stores history (old versions) of the records along with id.)

3. trigger.new (stores new version of the records.)

4. trigger.newMap (stores new version of the records along with id.)

2. 14.Availability of trigger.old and trigger.new for the different trigger

events?

Apex Trigger Collections availability for the different events -

trigger.o trigger.oldM trigger.n trigger.newM


Events
ld ap ew ap

before insert ✘ ✘ ✔ ✘

after insert ✘ ✘ ✔ ✔

before ✔ ✔ ✔ ✔
update

after update ✔ ✔ ✔ ✔

before
✔ ✔ ✘ ✘
delete

after delete ✔ ✔ ✘ ✘

after
✘ ✘ ✔ ✔
undelete

15.When to use before triggers and when to use after

triggers?

Before Triggers

1. To perform the validations we should use 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

contain the record id).

3.

16.For the same event if there are multiple triggers on the

object, how to control the order of

4. execution?

We cannot control the order of execution in this situation. It is recommended to

have only one trigger per one object.


5. 17.What are the recursive triggers and how to avoid?

If we perform update operation on the record in after update event logic

recursive triggers will arise.

Using static boolean variable in an apex class (we should not keep static boolean

variable inside of the trigger) we can avoid recursive triggers.

6. 18.What is the order of execution in salesforce?

Order of execution in salesforce - Order of execution in Salesforce:

1. Prepare the record for insert/update operation.

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

• pageLayout level validations

4. before triggers

5. Custom Validations and again system validation rules will fire (pageLayot

level validations won't fire at this point of time).

6. record will be saved into the database but doesn't not commit.

7. after triggers.

8. assignment rules.

9. auto-responsive rules.

10. Workflow 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.

12. Escalation Rules.


13. Rollup-Summary fields will be calculated.

14. Grant parent Rollup-Summary fields will be calculated.

15. Criteria base sharing evaluation.

16. Record will be committed into the database.

17. Post Commit logic (Sending emails).

19.What is Asynchronous Apex?

In a nutshell, asynchronous Apex is used to run processes in a separate thread,

at a later time.

An asynchronous process is a process or function that executes a task "in the

background" without the user having to wait for the task to finish.

7.

Type Overview Common Scenarios

Future Run in their own thread, and do not start


Web service callout.
Methods until resources are available.

Batch Run large jobs that would exceed normal Data cleansing or archiving of

Apex processing limits. records.

Similar to future methods, but provide Performing sequential


Queueable
additional job chaining and allow more processing operations with
Apex
complex data types to be used. external Web services.

Scheduled
Schedule Apex to run at a specified time. Daily or weekly tasks.
Apex

8.

20.About Future Method?

A future method runs in the background, asynchronously.


Future method syntax

1global class FutureClass {

2 @future

3 public static void myFutureMethod() {

4 // Perform some operations

5 }

6}

• Use @future annotation before the method declaration.

• Future methods must be static methods, and can only return a void type.

• The specified parameters must be primitive data types, arrays of primitive

data types, or collections of primitive data types.

• Future methods can’t take standard or custom objects as arguments.

• A common pattern is to pass the method a list of record IDs that you want

to process asynchronously.

1global class FutureMethodRecordProcessing {

2 @future

3 public static void processRecords(List<ID> recordIds){

4 // Get those records based on the IDs

5 List<Account> accts = [SELECT Name FROM Account WHERE Id IN :recordIds];

6 // Process records

7 }

8}
Future method callouts using @future(callout=true)

To allow callout from the future method annotation needs an extra parameter

(callout=true) to indicate that callouts are allowed. Here is example

1global class FutureMethodExample {

2 @future(callout=true)

3 public static void getStockQuotes(String acctName){

4 // Perform a callout to an external service

5 }

6}

20.About Batch apex method?

Batch Apex in Salesforce is specially designed for a large number of records,

i.e., here, data would be divided into small batches of records, and then it would be

evaluated. In other words, the Batch class in Salesforce is specifically designed to

process bulk data or records together and have a greater governor limit than the

synchronous code.

Advantages of Batch Apex in Salesforce

• Whenever a transaction is executed, Batch Apex ensures that the code

stays within the governor limit.

• Until a batch is not successfully executed, Batch Apex won’t execute the

following batches.

• A large set of records can be processed together regularly using Batch

Apex classes.
• The interface can be scheduled to run batches at different periods

• Asynchronous operations can be implemented by Batch Apex classes.

• 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.

Learn more about Salesforce from this Salesforce Training in New

York to get ahead in your career!

Why use Batch Apex in Salesforce instead of the normal Apex?

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.

• Retrieval of SOQL queries: Normal Apex can retrieve 50,000 SOQL

queries but, in Batch Apex, 50,000,000 SOQL queries can be retrieved.

• Heap size: Normal Apex has a heap size of 6 MB; whereas, Batch Apex has

a heap size of 12 MB.

• Errors: When executing bulk records, Normal Apex classes are more

vulnerable to encountering errors as compared to Batch Apex.

Get familiar with the top Salesforce Interview Questions to get a head

start in your career!

Batch Class in Salesforce

When using a Batch class in Salesforce, the batchable interface needs to be

implemented first. It has the following three methods:


• Start: This method is called at the starting of a batch job to collect the

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:

global void execute(Database.BatchableContext BC, list<sobject<) {}

• Execute: This method executes after the Start method, and it does the

actual processing for each batch, separately.

• Syntax:

global void execute(Database.BatchableContext BC, list<sobject<) {}

• Finish: This method will be called at last. Since this method is called in the

end, it is responsible to perform post-processing operations such as sending an

email. When this process is called all batches are already executed.

• Syntax:

global void finish(Database.BatchableContext BC) {}

Batch Class Schedule in Salesforce

You can schedule your Batch Apex class using the developer console or

scheduler. These Batch Classes can then be executed at a particular

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

execute at a particular time.


Below is an example of a Schedulable Apex class interface:

Global class apexScheduler implements Schedulable

Global void execute(SchedulableContext sc)

batchAccountUnpdate b=new batchAccountUpdate();

21. About Queueable Apex?

Differences between Future and queueable apex

Now let’s look at the main differences between Future and queueable apex

FUTURE APEX QUEUEABLE APEX

It is annotation based so we can use the It is a class which implements’ queueable

same apex class to write the future interface. Syntax: public class CLASS_NAME

method. Syntax: @future implements Queueable{}

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-

datatypes primitive data types.


The class which implements the Queueable interface are basically called

as Queueable apex class. This interface enables you to add jobs to the queue

and monitor them, which is an enhanced way of running your asynchronous

Apex code compared to using future methods. The interface has only one

method execute which takes the parameter of QueableContext.

It allows you to submit jobs for asynchronous processing similar to future

methods with with these additional benefits:

Non-primitive types: Your Queueable class can contain member variables of

non-primitive data types, such as sObjects or custom Apex types. Those

objects can be accessed when the job executes.

Monitoring: When you submit your job by invoking

the System.enqueueJob method, the method returns the ID of the AsyncApexJob

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

programmatically by querying your record from AsyncApexJob.

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:

This example is an implementation of the Queueable interface. The execute

method in this example inserts a new account.

1public class QueueableExample implements Queueable {

3 public void execute(QueueableContext context) {

4 Account acc = new Account(Name='Biswajeet');


5 Insert acc;

6 }

7}

To add this class as a job on the queue, call this method:

1ID jobID = System.enqueueJob(new AsyncExecutionExample());

The execution of a queued job counts once against the shared limit for asynchronous

Apex method executions.

• You can add up to 50 jobs to the queue with System.enqueueJob in a single

transaction.

• Limits.getQueueableJobs() helps to check how many queueable jobs have

been added in one transaction.

• No limit is enforced on the depth of chained jobs, which means that you

can chain one job to another job and repeat this.

• 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.

21.what is Scheduled Apex?

To invoke Apex classes to run at specific times, first implement

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

execution may be delayed based on service availability.

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

programmatically query the CronTrigger and CronJobDetail objects to get the

count of Apex scheduled jobs.

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

can be updated at a time.

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

Change Sets” in the Salesforce Help.

Implementing the Schedulable Interface

To schedule an Apex class to run at regular intervals, first write an Apex class

that implements the Salesforce-provided interface Schedulable.

The scheduler runs as system—all classes are executed, whether or not the user

has permission to execute the class.


To monitor or stop the execution of a scheduled Apex job using the Salesforce

user interface, from Setup, enter Scheduled Jobs in the Quick Find box, then

select Scheduled Jobs.

The Schedulable interface contains one method that must be

implemented, execute.

global void execute(SchedulableContext sc){}

The implemented method must be declared as global or public.

Use this method to instantiate the class you want to schedule.

Tip

Though it's possible to do additional processing in the execute method, we

recommend that all processing take place in a separate class.

The following example implements the Schedulable interface for a class

called mergeNumbers:

global class scheduledMerge implements Schedulable {

global void execute(SchedulableContext SC) {

mergeNumbers M = new mergeNumbers();

To implement the above class, execute this example in the Developer Console.

scheduledMerge m = new scheduledMerge();

String sch = '20 30 8 10 2 ?';

String jobID = system.schedule('Merge Job', sch, m);

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:

global class scheduledBatchable implements Schedulable {

global void execute(SchedulableContext sc) {

batchable b = new batchable();

database.executebatch(b);

An easier way to schedule a batch job is to call

the System.scheduleBatch method without having to implement

the Schedulable interface.

Use the SchedulableContext object to keep track of the scheduled job once it's

scheduled. The SchedulableContext getTriggerID method returns the ID of

the CronTrigger object associated with this scheduled job as a string. You can

query CronTrigger to track the progress of the scheduled job.

To stop execution of a job that was scheduled, use the System.abortJob method

with the ID returned by the getTriggerID 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

shown in this example.

CronTrigger ct =[SELECT TimesTriggered, NextFireTime FROM CronTrigger WHERE

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

of the current job by calling getTriggerId on the SchedulableContext argument

variable. Assuming this variable name is sc, the modified example becomes:

CronTrigger ct =

[SELECT TimesTriggered, NextFireTime

FROM CronTrigger WHERE Id = :sc.getTriggerId()];

You can also get the job’s name and the job’s type from the CronJobDetail record

associated with the CronTrigger record. To do so, use

the CronJobDetail relationship when performing a query on CronTrigger. This

example retrieves the most recent CronTrigger record with the job name and

type from CronJobDetail.

CronTrigger job =

[SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType

FROM CronTrigger ORDER BY CreatedDate DESC LIMIT 1];

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

queried in the previous example. The corresponding CronJobDetail record ID is

obtained by the CronJobDetail.Id expression on the CronTrigger record.

CronJobDetail ctd =

[SELECT Id, Name, JobType

FROM CronJobDetail WHERE Id = :job.CronJobDetail.Id];

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

type, which corresponds to the scheduled Apex job type.

SELECT COUNT() FROM CronTrigger WHERE CronJobDetail.JobType = '7'

You might also like