Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
39 views41 pages

Salesforce Apex Development Guide

The document provides an overview of Apex programming development, focusing on triggers, classes, asynchronous processes, and best practices for Salesforce. It covers trigger syntax, types, context variables, and the importance of bulkification, along with various asynchronous Apex methods such as Future, Batch, and Queueable. Additionally, it discusses transaction management, order of execution, and how to expose Apex classes as web services.

Uploaded by

lathasanthiya279
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views41 pages

Salesforce Apex Development Guide

The document provides an overview of Apex programming development, focusing on triggers, classes, asynchronous processes, and best practices for Salesforce. It covers trigger syntax, types, context variables, and the importance of bulkification, along with various asynchronous Apex methods such as Future, Batch, and Queueable. Additionally, it discusses transaction management, order of execution, and how to expose Apex classes as web services.

Uploaded by

lathasanthiya279
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit – IV

APEX PROGRAMMING DEVELOPMENT


Apex Trigger Essentials: Introduction - Trigger Events - Syntax - Trigger context
variables. Apex Class Implementation: Implement Business Logic in Apex class -
Trigger Handlers and Controllers - Best Practices (Bulkification, No DML & queries
inside loops) - Apex Test Classes. Advanced Apex: Asynchronous Apex - Apex
Scheduler - Batch Apex - Future methods - Queueable Apex API Callouts - Apex Web
Services - Standard APIs. Transactions: Lifecycle of a transaction – Memory life cycle
for static variable - Salesforce order of Execution - Execution Governor Limits.
Development Tools: Developer Console - Debug Logs - Eclipse & Force.com IDE -
Visual Studio - Workbench
Apex Trigger Essentials Introduction
• Apex triggers
• enable you to perform custom actions before or after events to records in
Salesforce,
• such as insertions, updates, or deletions.
• Just like database systems support triggers, Apex provides trigger support for
managing records.
• use triggers to perform operations based on specific conditions, to modify
related records or restrict certain operations
• use triggers to do anything you can do in Apex,
• including executing SOQL and DML or calling custom Apex methods.
Trigger Syntax
trigger TriggerName on ObjectName (trigger_events)
{
code_block
}
Types of Triggers
• Before triggers are used to update or validate record values before
they’re saved to the database.
• After triggers are used to access field values that are set by the
system (such as a record's Id or LastModifiedDate field), and to affect
changes in other records. The records that fire the after trigger are
read-only.
Trigger Events
• before insert
• before update
• before delete
• after insert
• after update
• after delete
• after undelete
Example
trigger HelloWorldTrigger on Account (before insert)
{
System.debug('Hello World!’);
}

Debug | Open Execute Anonymous Window


Account a = new Account(Name='Test Trigger’);
insert a;
Example
• This example is a modified version of the HelloWorldTrigger example
trigger. It iterates over each account in a for loop and updates the
Description field for each.
trigger HelloWorldTrigger on Account (before insert) {
for(Account a : Trigger.New) {
a.Description = 'New description';
}
}
Context Variables
• To access the records that caused the trigger to fire, use context
variables.
• new • newMap
• isExecuting • old
• isInsert
• oldMap
• isUpdate
• operationType
• isDelete
• size
• isBefore
• isAfter
Apex Class Implementation
• Calling methods of other classes enables
• code reuse
• reduces the size of your triggers
• improves maintenance of your Apex code.
• It also allows to use object-oriented programming
• Example
• The EmailManager class is included in the class example of the Get Started
with Apex unit. You must have saved the EmailManager class in your org and
changed the sendMail() method to static before saving this trigger.
Implement Business Logic in Apex class
trigger ExampleTrigger on Contact (after insert, after delete) {
if (Trigger.isInsert) {
Integer recordCount = Trigger.New.size();
// Call a utility method from another class
EmailManager.sendMail('[email protected]', 'Trailhead Trigger Tutorial',
recordCount + ' contact(s) were inserted.');
}
else if (Trigger.isDelete) {
// Process after delete
}
}
Trigger Handlers and Controllers
• a trigger handler is the starting point to 'handle' complex logic set
into a trigger.
• Creating a class defined as MyObjectTriggerHandler can help to
design a modular set of reusable objects which manage all the
operations to be done by a trigger.
Best Practices
• Bulkification
• Apex triggers are optimized to operate in bulk
• use bulk design patterns,
• triggers have better performance
• consume less server resources
• less likely to exceed platform limits.
• Benefit of bulkifying your code
• is that bulkified code can process large numbers of records efficiently and run within
governor limits on the Lightning Platform.
• These governor limits are in place to ensure that runaway code doesn’t monopolize
resources on the multitenant platform.
Bulkification ctd……..
• Bulkifying your Apex code in triggers:
• operating on all records in the trigger, and performing SOQL and DML on
collections of sObjects instead of single sObjects at a time.
• The SOQL and DML bulk best practices apply to any Apex code, including
SOQL and DML in classes.
• Operating on Record Sets
• bulk DML or the API, the trigger operates on a record set rather than one
record
Example - Bulkification
• The following trigger assumes that only one record caused the trigger
to fire. – MyTriggerNotBulk

• trigger MyTriggerNotBulk on Account(before insert) { Account a =


Trigger.New[0]; a.Description = 'New description’; }

• It uses a for loop to iterate over all available sObjects. This loop
works if Trigger.New contains one sObject or many sObjects. -
MyTriggerBulk
• trigger MyTriggerBulk on Account(before insert) { for(Account a : Trigger.New)
{ a.Description = 'New description'; } }
Account a = new Account(Name='Test Trigger');
insert a;
Bulk SOQL
• Retrieve related records and check a combination of multiple conditions in
one query.
• Example makes a SOQL query inside a for loop to get the related
opportunities for each account, which runs once for each Account sObject
in Trigger.New
trigger SoqlTriggerNotBulk on Account(after update)
{
for(Account a : Trigger.New)
{
Opportunity[] opps = [SELECT Id,Name,CloseDate FROM Opportunity WHERE AccountId=:a.Id];
}
}
Bulk SOQL - Example
trigger SoqlTriggerBulk on Account(after update) {
List<Account> acctsWithOpps =
[SELECT Id,(SELECT Id,Name,CloseDate FROM Opportunities)
FROM Account WHERE Id IN :Trigger.New];

for(Account a : acctsWithOpps) {
Opportunity[] relatedOpps = a.Opportunities;
}
}
Bulk DML
• DML calls in a trigger or in a class, perform DML calls on a collection
of sObjects
• Performing DML on each sObject individually uses resources
inefficiently
• Apex runtime allows up to 150 DML calls in one transaction.
• Trigger performs an update call inside a for loop that iterates over
related opportunities. If certain conditions are met, the trigger
updates the opportunity description.
Example – Bulk DML
trigger DmlTriggerNotBulk on Account(after update) {
List<Opportunity> relatedOpps = [SELECT Id,Name,Probability FROM
Opportunity WHERE AccountId IN :Trigger.New];
for(Opportunity opp : relatedOpps) {
if ((opp.Probability >= 50) && (opp.Probability < 100)) {
opp.Description = 'New description for opportunity.';
update opp;
}
}
}
Example – Bulk DML cntd….
trigger DmlTriggerBulk on Account(after update) {
List<Opportunity> relatedOpps = [SELECT Id,Name,Probability FROM Opportunity
WHERE AccountId IN :Trigger.New];
List<Opportunity> oppsToUpdate = new List<Opportunity>();
for(Opportunity opp : relatedOpps) {
if ((opp.Probability >= 50) && (opp.Probability < 100)) {
opp.Description = 'New description for opportunity.';
oppsToUpdate.add(opp);
}
}
update oppsToUpdate;
}
Test Apex Triggers
• Before deploying a trigger, write unit tests to perform the actions that fire
the trigger and verify expected results.
• Example - AccountDeletion trigger prevents the record’s deletion.

Trigger AccountDeletion on Account (before delete) {


for (Account a : [SELECT Id FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity) AND
Id IN :Trigger.old]) {
Trigger.oldMap.get(a.Id).addError(
'Cannot delete account with related opportunities.');
}
}
Adding and Running a Unit Test
trigger AccountDeletion on Account (before delete) {

for (Account a : [SELECT Id FROM Account


WHERE Id IN (SELECT AccountId FROM Opportunity) AND
Id IN :Trigger.old]) {
Trigger.oldMap.get(a.Id).addError(
'Cannot delete account with related opportunities.');
}

}
@isTest
private class TestAccountDeletion {
@isTest static void TestDeleteAccountWithOneOpportunity() {
Account acct = new Account(Name='Test Account');
insert acct;
Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
StageName='Prospecting',
CloseDate=System.today().addMonths(1),
AccountId=acct.Id);
insert opp;
Database.DeleteResult result = Database.delete(acct, false);
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
System.assertEquals('Cannot delete account with related opportunities.',
result.getErrors()[0].getMessage());
}
}
Asynchronous Apex
• 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
• Asynchronous Apex for callouts to external systems, operations that
require higher limits, and code that needs to run at a certain time.
• key benefits
• User efficiency
• Scalability
• Higher Limits
Asynchronous Apex comes in a number of
different flavors.
Type Overview Common Scenarios
Future Methods Run in their own thread, and do Web service callout.
not start until resources are
available.
Batch Apex Run large jobs that would exceed Data cleansing or archiving of
normal processing limits. records.
Queueable Apex Similar to future methods, but Performing sequential processing
provide additional job chaining and operations with external Web
allow more complex data types to services.
be used.
Scheduled Apex Schedule Apex to run at a specified Daily or weekly tasks.
time.
Future Apex
• Future Apex is used to run processes in a separate thread, at a later
time when system resources become available.
• @future annotation to identify methods that run asynchronously.
• Future methods are typically used for:
• Callouts to external Web services.
• Operations you want to run in their own thread, when time permits such as
some sort of resource-intensive calculation or processing of records.
• Isolating DML operations on different sObject types to prevent the mixed
DML error.
Future Method Syntax
• Future methods must be static methods, and can only return a void type.

global class SomeClass


{
@future
public static void someFutureMethod(List<Id> recordIds)
{
List<Account> accounts = [Select Id, Name from Account Where Id IN :recordIds];
}
}

https://trailhead.salesforce.com/content/learn/modules/asynchronous_apex/async_apex_future_m
ethods
Batch Apex
• Batch Apex is used to run large jobs (think thousands or millions of
records!) that would exceed normal processing limits.
• Advantages:
• Every transaction starts with a new set of governor limits, making it easier to ensure
that your code stays within the governor execution limits.
• If one batch fails to process successfully, all other successful batch transactions aren’t
rolled back.
• Batch Apex Syntax
• To write a Batch Apex class, your class must implement the Database.Batchable
interface and include the following three methods:
• Start
• Execute
• finish
skeleton of a Batch Apex class
global class MyBatchClass implements Database.Batchable<sObject> {
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc)
// collect the batches of records or objects to be passed to execute
}
global void execute(Database.BatchableContext bc, List<P> records){
// process each batch of records
}
global void finish(Database.BatchableContext bc){
// execute any post-processing operations
}
}
Invoking a Batch Class
MyBatchClass myBatchObject = new MyBatchClass();
Id batchId = Database.executeBatch(myBatchObject);

https://trailhead.salesforce.com/content/learn/modules/asynchronous
_apex/async_apex_batch
Queueable Apex API Callouts
• Queueable Apex allows you to submit jobs for asynchronous processing similar to future methods
with the following additional benefits:
• Non-primitive types
• Monitoring
• Chaining jobs
• Queueable Syntax
• simply imple
public class SomeClass implements Queueable
{
public void execute(QueueableContext context)
{
// awesome code here
}
}

https://trailhead.salesforce.com/content/learn/modules/asynchronous_apex/async_apex_queueable
Scheduled Apex
• The Apex Scheduler lets you delay execution so that you can run Apex
classes at a specified time.
• write an Apex class that implements the Schedulable interface, and then
schedule it for execution on a specific schedule.
• Scheduled Apex Syntax
global class SomeClass implements Schedulable {
global void execute(SchedulableContext ctx) {
// awesome code here
}
}
https://trailhead.salesforce.com/content/learn/modules/asynchronous_apex/async_a
pex_scheduled
Apex Web Services
• You can expose your Apex class methods as a REST or SOAP web service
operation.
• By making your methods callable through the web, your external applications can
integrate with Salesforce to perform all sorts of nifty operations.
• Expose a Class as a REST Service

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
@HttpGet
global static Account getRecord() {
// Add your code
}
}
Annotations

Annotation Action Details


@HttpGet Read Reads or retrieves records.
@HttpPost Create Creates records.
@HttpDelete Delete Deletes records.
@HttpPut Upsert Typically used to update existing
records or create records.
@HttpPatch Update Typically used to update fields in
existing records.
Expose a Class as a SOAP Service
global with sharing class MySOAPWebService {
webservice static Account getRecord(String id)
{
// Add your code
}
}

https://trailhead.salesforce.com/en/content/learn/modules/apex_inte
gration_services/apex_integration_webservices
Standard APIs
• An API is equivalent to a user interface, except it’s designed for
software instead of humans.
• The electricity coming from the
wall is a service. It can stop and
start at any time.
• The treadmill plugged into the
wall uses the electricity to run.
• Since the treadmill does not have
its own source of power, the
treadmill is outsourcing the
power it needs from the service
provider, for example windmills
or solar power.
Transactions
• An Apex transaction represents a set of operations that are executed
as a single unit.
• All DML operations in a transaction either complete successfully,
• or 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.
Order of Execution
• When you save a record with an insert, update, or upsert statement,
Salesforce performs the following events in order.
• On the server, Salesforce:
1. Loads the original record from the database or initializes the record for an
upsert statement.
2. Loads the new record field values from the request and overwrites the old
values.
3. Executes all before triggers.
4. Runs most system validation steps again
5. Executes duplicate rules.
Order of Execution ctd….
6. Executes all after triggers.
7. Executes assignment rules.
8. Executes auto-response rules.
9. Executes workflow rules.
10. If there are workflow field updates, updates the record again.
11. If the record was updated with workflow field updates, fires before
update triggers and after update triggers one more time
12. Executes processes and flows launched via processes and flow trigger
workflow actions.
13. Executes escalation rules.
14. Executes entitlement rules.
Order of Execution ctd….
15. If the record contains a roll-up summary field or is part of a cross-object
workflow, performs calculations and updates the roll-up summary field in
the parent record. Parent record goes through save procedure.
16. If the parent record is updated, and a grandparent record contains a roll-
up summary field or is part of a cross-object workflow, performs
calculations and updates the roll-up summary field in the grandparent
record. Grandparent record goes through save procedure.
17. Executes Criteria Based Sharing evaluation.
18. Commits all DML operations to the database.
19. Executes post-commit logic, such as sending email.
Execution Governor Limits
• Governor execution limits ensure the efficient use of resources on the
Force.com multitenant platform.
• It is the limit specified by the Salesforce.com on code execution for
efficient processing.
• Avoiding SOQL Query Limit
• You can issue only 100 queries per transaction, that is, when your
code will issue more than 100 SOQL queries then it will throw error.

• https://www.tutorialspoint.com/apex/apex_governor_limits.htm
Development Tools
• Developer Console
• Debug Logs
• Eclipse & Force.com IDE
• Visual Studio – Workbench

• https://trailhead.salesforce.com/en/content/learn/projects/set-up-
your-lightning-web-components-developer-tools/install-
development-tools

You might also like