SPD Unit-2-1
SPD Unit-2-1
R-22
MR22-1CS0155
What is Apex?
❑ Apex is a strongly typed, object-oriented programming language developed
by Salesforce.
❑ It is used primarily for building custom business logic within the Salesforce
platform (Force.com).
❑ Apex uses Java-like syntax and acts like database stored procedures.
❑ It enables developers to add business logic to system events, such as button clicks,
updates of related records.
For Example
Introduction to Apex
Features of Apex:
⮚Integrated with the database - It provides direct access to records and their fields, and provides
⮚Data focused - Apex provides transactional access to the database, allowing you to roll back
operations.
Introduction to Apex
⮚ Easy to test - Apex provides built-in support for unit test creation, execution, and code coverage.
Salesforce ensures that all custom Apex code works as expected by executing all unit tests prior
to any platform upgrades.
⮚ Versioned - Custom Apex code can be saved against different versions of the API.
⮚ Integrated with DML & APIs - Apex has in-built DML activities like Insert, Delete, Update and
DML exemption dealing with. It upholds loops that permit the handling of numerous records all
at once.
Introduction to Apex
Introduction to Apex - Data Types
•The Apex language is strongly typed so every variable in Apex will be declared with the specific data
type.
•All apex variables are initialized to null initially.
•It is always recommended for a developer to make sure that proper values are assigned to the
variables.
•Otherwise such variables when used, will throw null pointer exceptions or any unhandled exceptions.
Types:
• Primitive Data types
• sObject
• Collections
• Enum
Introduction to Apex - Data Types
Primitive Data types:
⮚Integer:
A 32-bit number that does not include any decimal point.
Example:
Integer barrelNumbers = 1000;
System.debug(' value of barrelNumbers variable: '+barrelNumbers);
⮚Long:
This is a 64-bit number without a decimal point. This is used when we need a range of values
wider than those provided by Integer.
Example:
Long companyRevenue = 21474838973344648L;
System.debug('companyRevenue'+companyRevenue);
Introduction to Apex - Data Types
⮚ Double:
A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and a
maximum value of 263-1.
Example:
Double pi = 3.14159;
Double e = 2.7182818284D;
⮚ Boolean:
This variable can either be true, false or null.
Example:
Boolean shipmentDispatched;
shipmentDispatched = true;
System.debug('Value of shipmentDispatched '+shipmentDispatched);
Introduction to Apex - Data Types
⮚ Date:
This variable type indicates a date. This can only store the date and not the time. For saving the
date along with time, we will need to store it in variable of DateTime.
Example:
Date ShipmentDate = date.today();
System.debug('ShipmentDate '+ShipmentDate);
⮚ Datetime:
A value that indicates a particular day and time, such as a timestamp. Always create datetime
values with a system static method.
⮚ Time:
This variable is used to store the particular time. This variable should always be declared with the
system static method.
Introduction to Apex - Data Types
⮚ String:
String is any set of characters within single quotes. It does not have any limit for the number of
characters.
Example:
String companyName = 'Abc International';
System.debug('Value companyName variable'+companyName);
⮚ ID:
When inserting records, the system assigns an ID for each record.
Any valid 18-character Lightning Platform record identifier.
If you set ID to a 15-character value, Apex converts the value to its 18-character representation.
All invalid ID values are rejected with a runtime exception.
Example:
ID id='00300000003T2PGAA0';
Introduction to Apex - Data Types
sObject:
- In Apex, the sObject data type represents Salesforce objects, both standard and custom.
- Each Salesforce record is represented as an sObject before it is inserted into Salesforce.
- It‟s a versatile data type used to interact with any record in Salesforce, encompassing fields,
relationships, and metadata.
- sObjects are fundamental for CRUD operations, enabling robust data management and
manipulation.
- This is a special data type in Apex. sObject is a generic data type for representing an Object
that exists in Force.com.
Types:
• Specific sObject
• Generic sObject
Introduction to Apex - Data Types
⮚ Specific sObject:
The API object name becomes the data type of the sObject variable in Apex.
For Example, Account is a datatype for a standard object “Account” and Student__c for a
custom object called “Student”, when working with sObjects.
Example:
For Standard Object:
Account acc=new Account();
Here,
Account = sObject datatype
acc = sObject variable
new = Keyword to create new sObject Instance
Account() = Constructor which creates an sObject instance
EXAMPLE:
(i) Adding values to Fields through constructor by specify them as name-value pairs inside the
constructor
Account acct = new Account(Name='Ajay', Phone=‗9856745923', NumberOfEmployees=100);
System.debug(acct.Name);
(ii) SObject fields can be accessed or changed with simple dot notation.
Account acct = new Account ();
acct.Name = Acc1;
acct.BillingCity = Washington;
Introduction to Apex - Data Types
Generic sObject:
• Generic sObject data type is used to declare the variables which can store any type of
sObject instance.
• We use when we don't know the type of sObject our method is handling,
• Variables that are declared with the generic sObject data type can reference any Salesforce
record, whether it is a standard or custom object record.
Introduction to Apex - Data Types
• In Salesforce, you can cast a generic sObject to a specific sObject type using the
sObject's API name.
• One of the benefits of doing so is to be able to access fields using dot notation, which
is not available on the generic sObject.
• Since sObject is a parent type for all specific sObject types, you can cast a generic
sObject to a specific sObject.
Introduction to Apex - Data Types
Example:
sObject s1;
s1=new Account();
Account acc = (Account) s1;
acc.Name='Ajay';
system.debug(acc.Name);
s1=new Contact();
Contact con = (Contact) s1;
con.MobilePhone='98764597';
system.debug(con.MobilePhone);
Types of Collections
• Salesforce has three types of collections:
1. List collection
2. Set collection
3. Map collection
Introduction to Apex - Data Types
1. List:
• A list is an ordered collection of elements that are distinguished by their indices.
• ―List‖ is the keyword to declare a list collection.
• Each list index begins with 0.
• The list can store duplicate and null values.
• The list keyword followed by the data type has to be used within <> characters to define a list
collection.
• List elements can be of any data type—primitive types, collections, sObjects, user-defined types,
and built-in Apex types.
Syntax for a list is as follows:
List<datatype> listName = new List<datatype>();
Example:
List<String> colors = new List<String>();
OUTPUT
Introduction to Apex - Data Types
2. Set:
• A set is an unordered collection of elements.
• Insertion order is not preserved in the set.
• A Set cannot have duplicate records. Like Lists, Sets can be nested.
• You cannot perform DML with Set.
• You can't index a Set like you can a List/Array.
• You can perform typical set operations - such as check if the Set contains an element by value,
or
remove an element by value.
Syntax for a Set is as follows:
Set<datatype> variablename = new Set<datatype>();
Example:
Set<string> ProductSet = new Set<string> {'Phenol', 'Benzene', 'H2SO4'};
System.debug('Value of ProductSet'+ProductSet);
Set Constructors:
Constructors for Set includes:
1. Set() - It helps in creating a new instance of the Set class. It can hold elements of any data type
T.
Set<String> s = new Set<String>{‗XYZ‘};
2. Set(setToCopy) - It helps in creating a new instance of the Set class by copying the elements
of the defined Set. T is the data type of the element sets.
Set<String> s = new Set<String>{'XYZ'};
Set<String> s1 = new Set<String>(s);
System.debug(s1);
3. Set(listToCopy) - It helps in creating a new instance of the Set class by copying the elements
in the list. The list can be any data type and the data type of element in the Set is T.
list<String> L = new list<String>{'XYZ'};
Set<String> s1 = new Set<String>(L);
System.debug(s1);
Some common methods of set in Apex:
S.No Function Example
Set<String> s = new Set<String>{‗XYZ‘};
add(Element)
s.add(‗abc‘);
Adds an element to set and only takes the
1 s.add(‗ABC‘);
argument of special datatype while declaring
s.add(‗abc‘);
the set.
System.debug(s); //(ABC, XYZ, abc)
List<String> l = new List<String>();
addAll(list/set)
l.add(‗abc‘);
Adds all of the elements in the specified
2 l.add(‗def‘);
list/set to the set if they are not already
s.addAll(l);
present.
System.debug(s); //(ABC, XYZ, abc, def)
clear() s.clear();
3
Removes all the elements. s.addAll(l);
clone() set<String> s2 = s.clone();
4
Makes duplicate of a set. System.debug(s2); //(ABC, XYZ, abc, def)
contains(elm)
Boolean result = s.contains(‗abc‘);
5 Returns true if the set contains the specified
System.debug(result); // true
element.
S.No Function Example
containsAll(list)
Returns true if the set contains all of the
Boolean result = s.containsAll(l);
6 elements in the specified list. The list must be
System.debug(result); // true
of the same type as the set that calls the
method.
size()
7 System.debug(s.size()); // 2
Returns the size of set.
retainAll(list)
s.add(‗ghi‘);
Retains only the elements in this set that are
System.debug(s); //(ABC,XYZ,abc,def,ghi)
8 contained in the specified list and removes all
s.retainAll(l);
other elements. This method results in
System.debug(s); //(‗abc‘,‘def‘)
the intersection of the list and the set.
remove(elm) s.add(‗ghi‘);
9 Removes the specified element from the set if s.remove(‗ghi‘);
it is present. System.debug(s); //(‗abc‘,‘def‘)
removeAll(list) s.add(‗ghi‘);
10 Removes the elements in the specified list s.removeAll(list);
from the set if they are present. System.debug(s); //(‗ghi‘)
Introduction to Apex - Data Types
Example:
Set<String> ProductSet=new Set<String>();
ProductSet.add('HCL');
ProductSet.add('H2O');
ProductSet.add('H2SO4');
System.debug('Set with New Value: '+ProductSet);
ProductSet.remove('HCL');
System.debug('Set with removed value: '+ProductSet);
System.debug (ProductSet.contains('HCL'));
System.debug (ProductSet. size());
System.debug('Value of Set with all values '+ProductSet);
Introduction to Apex - Data Types
3. Map:
• It is a key value pair which contains the unique key for each value.
• Map values may be unordered and hence we should not rely on the order in which the values
are stored and try to access the map always using keys.
i.e., ABC and abc will be considered as different keys and treated as unique.
Map<string, string> map1 = new Map<string, string> {'1000'=>'HCL', '1001'=>'H2SO4'};
Map Initialization
1. Initialize a Map with String Keys and Integer Values:
Map<String, Integer> myMap = new Map<String, Integer> {
‗One‘ => 1,
‗Two‘ => 2,
‗Three‘ => 3
};
2. Using Constructor You can initialize a map using the constructor and then add entries:
Map<String, Integer> myMap = new Map<String,
Integer>();
myMap.put('Key1', 1);
myMap.put('Key2', 2);
3. Initialize a Map with String Keys and Custom Object Values:
MyCustomObject__c obj1 = new MyCustomObject__c(Name = ‗Object1‘);
MyCustomObject__c obj2 = new MyCustomObject__c(Name = ‗Object2‘);
Map<String, MyCustomObject__c> myMap = new Map<String,
MyCustomObject__c>{‗Key1‘ => obj1, ‗Key2‘ => obj2 };
S.No Function Example Output
Example 1:
system.debug(map1.get(‗1000‘));
map1.put('1000','H20');
System.debug(map1.get('1000'));
Example 2:
system.debug(map1.get(1000));
Iterating Through a Map using for loop
Map<String, Integer> myMap = new Map<String, Integer>{ 'a' => 1, 'b' => 2};
for (string key : myMap.keySet())
{
integer value = myMap.get(key);
System.debug('Key: ' + key + ', Value: ' + value);
}
Enum:
• An Enum, short for enumeration, in Salesforce Apex is a user defined data type to define a set
of named constants.
• Programmers use Enum to create a collection of related values that can be used to make code
• This ensures that the values are consistent across the application.
• For instance, you might use an Enum to represent the days of the week, months in a year, or the
•Enum contain fixed constant values, which makes code less prone to errors caused by using
undefined values.
•These values are stored as named constants, making code easier to read and maintain.
•Enum provide a way to group and manage related sets of constants in an organized manner.
To define an enum, use the enum keyword in your declaration and use curly braces to demarcate
the list of possible values.
Introduction to Apex - Data Types
The following code creates an enum called Season:
public enum Season {WINTER, SPRING, SUMMER, FALL}
By creating the enum Season, you have also created a new data type called Season.
Enum Methods:
All Apex enums, whether user-defined enums or built-in enums, have the following common
methods that takes no arguments.
values : This method returns the values of the Enum as a list of the same Enum type.
ordinal : Returns the position of the item, as an Integer, in the list of Enum values starting with zero.
Example:
System.debug(Animal.values());
System.debug(Animal.Lion.name());
System.debug(Animal.Penguin.ordinal());
System.debug(Animal.valueOf('Lion'));
Apex Classes
Create an Apex Class:
The Developer Console is where you write and test your code in Salesforce.
Steps to create an Apex class:
• Click the gear icon to access Setup in Lightning Experience and select Developer Console.
• From the File menu, select New | Apex Class.
• For the class name, enter Person and then click OK.
Syntax:
AccessModifier class ClassName {
data members;
methods; }
Apex Classes
Declaring a method Example
The syntax to declare an Apex method is:
public class Person
{
public class MyClass { public String name;
public ReturnType methodName() public Integer age;
{ public void sayName()
return ReturnValue; } { System.debug('My name is ' + name); }
} public void sayAge()
{ System.debug('I am ' + age); } }
Here,
• public: This means that you can use your method in any application within your org.
• methodName: An identifier that you will use to call your method and execute logic within the method.
• ReturnType: Any data type that your method returns. See the return statement section.
• ReturnValue: Value that is returned from the method back to the calling function.
Apex Classes
Run the Code:
• An anonymous block is Apex code that does not get stored, but can be compiled
and executed on demand right from the Developer Console.
• This is a great way to test your Apex Classes or run sample code.
OUTPUT
Apex Classes
Constructor in Apex:
The constructor is a special method .
The Method name will be the same as a class.
Access specifier will be public.
This method will be invoked only once that is at the time of creating an object.
This is used to instantiate the data members of the class.
Constructor will not have a return type.
1. Default Constructor
If an Apex Class doesn't contain any constructor then Apex compiler by default creates a
dummy constructor on the name of the class when we create an object for the class.
The default constructor literally does nothing!
2. Non-parameterized Constructor
It is a constructor that doesn't have any parameters is called Non-parameterized constructor.
Parameters are nothing but the values we are passing inside a constructor.
3. Parameterized Constructor
It is a constructor that has parameters.
That means here we will take input from the user and then map it with our variable.
Apex Classes
public class Employee //Class
{ String EmployeeName='Anil'; Execute Anonymous Window
Integer EmployeeNo=01;
public Employee( ) //Non-Parameterized Constructor
{ System.debug('Employee Name is '+ EmployeeName);
System.debug('Employee No is '+ EmployeeNo);
EmployeeName = 'Karthik';
EmployeeNo = 10;
OUTPUT
System.debug('Employee Name is '+ EmployeeName);
System.debug('Employee No is '+ EmployeeNo); }
public Employee(string Name, integer num) //Parameterized Constructor
{ System.debug('Employee Name is '+ EmployeeName);
System.debug('Employee No is '+ EmployeeNo);
EmployeeName = Name;
EmployeeNo = num; }
public void show() //Method
{ System.debug('Employee Name is '+ EmployeeName);
System.debug('Employee No is '+ EmployeeNo); } }
Database structure
Manipulate Records with DML:
• Because Apex is a data-focused language and is saved on the Lightning Platform, it has direct access
to your data in Salesforce.
• By calling DML statements, you can quickly perform operations on your Salesforce records.
• DML allows you to perform operations on a single sObject record or in bulk on a list of sObjects
records at once.
• Operating on a list of sObjects is a more efficient way for processing records.
• Insert
• Delete
• Update
• Undelete
• Upsert
• Merge
Insert operation is used to create new records in Database. You can create records of any Standard or
Insert st;
Insert st;
Database structure
Update Branch record:
The update DML operation modifies one or more existing sObject records. update is analogous to the
UPDATE statement in SQL.
Branch__c branch=[Select Branch_Name__c from Branch__c where
Branch_Name__c='Information Technology'];
branch.Branch_Name__c='IT';
update branch;
You can undelete the record which has been deleted and is present in Recycle bin. All the relationships
The ALL ROWS keyword queries all rows for both top level and aggregate relationships, including deleted
ALL ROWS];
undelete branch;
Database structure
Upsert:
• If you have a list containing a mix of new and existing records, you can process insertions and updates
to all records in the list by using the upsert statement.
• Upsert helps avoid the creation of duplicate records and can save you time as you don‟t have to
determine which records exist first.
• The upsert statement matches the sObjects with existing records by comparing values of one field.
• If you don‟t specify a field when calling this statement, the upsert statement uses the sObject‟s ID to
match the sObject with existing records in Salesforce.
• If the key isn‟t matched, then a new object record is created.
• If the key is matched once, then the existing object record is updated.
• If the key is matched multiple times, then an error is generated and the object record is not
inserted or updated.
Database structure
Upsert Syntax:
• This example shows how upsert inserts a new branch and updates an existing branch name in
branch record in one call.
• This upsert call inserts a new Branch „Data Science‟ and updates the existing Branch Name
„Information Technology to „IT‟.
Branch__c br1 = new Branch__c (Branch_Name__c ='Data Science'); //new branch created
Branch__c br2=[Select Branch_Name__c from Branch__c where Branch_Name__c ='Information
Technology'];
br2. Branch_Name__c ='IT'; //change branch name
List<Branch__c> bran = new List<Branch__c> { br1, br2 }; // List to hold the new contacts to upsert
upsert bran;
Database structure
Merge:
• When you have duplicate lead, contact, case, or account records in the database, cleaning up your data
and consolidating the records might be a good idea.
• The merge operation merges up to three records into one of the records, deletes the others, and
reparents any related records.
List < Account > accList = [SELECT Name FROM Account LIMIT 3];
Account a = accList[0];
Account b = accList[1];
Account c = accList[2];
List < Account > mergeList = new List < Account > ();
mergeList.add(accList[1]);
mergeList.add(accList[2]);
merge a b; // for 2 records
merge a mergeList; // for 3 records
Note:
● Merge only works with Accounts, Leads and Contacts.
● You can merge 3 records at a time not more than that.
Database structure
DML Statement Exceptions
• If a DML operation fails, it returns an exception of type DmlException.
• You can catch exceptions in your code to handle error conditions.
This example produces a DmlException because it attempts to insert an account without the required Name field. The
exception is caught in the catch block.
try {
Account acct = new Account(); // This causes an exception because the required Name field is not provided.
insert acct; // Insert the account
} catch (DmlException e) {
System.debug('A DML exception has occurred: ' + e.getMessage()); }
Database structure
Bulk DML:
• You can perform DML operations either on a single sObject, or in bulk on a list of sObjects.
• This limit is in place to ensure fair access to shared resources in the Lightning Platform.
• Performing a DML operation on a list of sObjects counts as one DML statement, not as one statement
Database Methods
Apex contains the built-in Database class, which provides methods that perform DML operations and
mirror the DML statement counterparts.
These Database methods are static and are called on the class name.
● Database.insert()
● Database.update()
● Database.upsert()
● Database.delete()
● Database.undelete()
● Database.merge()
Execute SOQL and SOSL Queries
Execute SOQL and SOSL Queries
● SELECT fields : This part lists the fields that you would like to retrieve. The fields are specified after the
SELECT keyword in a comma-delimited list. Or you can specify only one field, in which case no comma is
necessary.
● FROM ObjectName : This part specifies the standard or custom object that you want to retrieve. In this example,
it‟s Account. For a custom object called Student, it is Student__c.
For example, the following retrieves all account records with two fields, Name and Phone, and returns an array of
Account sObjects.
Account[] accts = [SELECT Name, Phone FROM Account];
Execute SOQL and SOSL Queries
• If you have more than one account in the org, they will all be returned.
• If you want to limit the accounts returned to accounts that fulfill a certain condition, you can add this condition
inside the WHERE clause.
• The following example retrieves only the accounts whose names are SFDC Computing.
The WHERE clause can contain multiple conditions that are grouped by using logical operators (AND, OR)
and parentheses.
For example, this query returns all accounts whose name is SFDC Computing that have more than 25 employees:
This example sorts all retrieved accounts based on the Name field.
SELECT Name, Phone FROM Account ORDER BY Name
The default sort order is in alphabetical order, specified as ASC. The previous statement is equivalent to:
SELECT Name, Phone FROM Account ORDER BY Name ASC
To reverse the order, use the DESC keyword for descending order:
SELECT Name, Phone FROM Account ORDER BY Name DESC
NOTE:
• You can sort on most fields, including numeric and text fields.
• You can‟t sort on fields like rich text and multi-select picklists.
Execute SOQL and SOSL Queries
You can limit the number of records returned to an arbitrary number by adding the LIMIT n clause, where n is
the number of records you want to be returned.
Limiting the result set is handy when you don‟t care which records are returned, but you just want to work with a
subset of records.
For example, this query retrieves the first account that is returned.
Notice that the returned value is one account and not an array when using LIMIT 1.
Execute the following SOQL query in Apex by using the Execute Anonymous window in the Developer Console. Then
inspect the debug statements in the debug log. One sample account should be returned.
Account[] accts = [SELECT Name, Phone FROM Account WHERE (Name='SFDC Computing' AND
NumberOfEmployees>25) ORDER BY Name LIMIT 10];
System.debug(accts.size() + ' account(s) returned.');
System.debug(accts); // Write all account array info
Execute SOQL and SOSL Queries
This example shows how to use the targetDepartment variable in the WHERE clause.
Both variable and variable_list must be of the same type as the sObjects that are returned by the soql_query.
It is preferable to use the sObject list format of the SOQL for loop as the loop executes once for each batch of 200
sObjects.
Execute SOQL and SOSL Queries
Example:
insert new Account[]{new Account(Name = 'for loop 1'),
Integer i=0;
for (Account[] tmp : [SELECT Id FROM Account WHERE Name LIKE 'for loop '])
System.debug(tmp[i]);
i++;
}
Execute SOQL and SOSL Queries
Write SOSL Queries:
Salesforce Object Search Language (SOSL) is a Salesforce search language that is used to perform
text searches in records.
Use SOSL to search fields across multiple standard and custom object records in Salesforce. SOSL is
similar to Apache Lucene.
Adding SOSL queries to Apex is simple—you can embed SOSL queries directly in your Apex code.
When SOSL is embedded in Apex, it is referred to as inline SOSL.
Remember that in the Query Editor and API, the syntax is slightly different:
FIND {SearchQuery} [IN SearchGroup] [RETURNING ObjectsAndFields]
This is an example of a SOSL query that searches for accounts and contacts that have any fields with the word 'SFDC'.
● ALL FIELDS
● NAME FIELDS
● EMAIL FIELDS
● PHONE FIELDS
● SIDEBAR FIELDS
ObjectsAndFields is optional.
It is the information to return in the search result—a list of one or more sObjects and, within each sObject, list of
one or more fields, with optional values to filter against. If not specified, the search results contain the IDs of all
objects found.
Execute SOQL and SOSL Queries
Single Words and Phrases:
A SearchQuery contains two types of text:
● Single Word— single word, such as test or hello. Words in the SearchQuery are delimited by spaces, punctuation,
and changes from letters to digits (and vice-versa). Words are always case insensitive.
● Phrase— collection of words and spaces surrounded by double quotes such as "john smith". Multiple words can be
combined together with logic and grouping operators to form a more complex query.
SOSL Apex Example:
The SOSL query references this local variable soslFindClause by preceding it with a colon, also called
binding.
String soslFindClause = 'Wingo OR SFDC';
List<List<sObject>> searchList = [FIND :soslFindClause IN ALL FIELDS RETURNING Account(Name),
Contact(FirstName,LastName,Department)];
Account[] searchAccounts = (Account[])searchList[0];
Contact[] searchContacts = (Contact[])searchList[1];
System.debug('Found the following accounts.');
for (Account a : searchAccounts) { System.debug(a.Name); }
System.debug('Found the following contacts.');
for (Contact c : searchContacts) { System.debug(c.LastName + ', ' + c.FirstName); }
Execute SOQL and SOSL Queries
Differences and Similarities Between SOQL and SOSL
Apex Triggers - Introduction
• A trigger is a set of Apex code that runs before or after Data manipulation language (DML) events.
• It enables 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.
• Typically, you use triggers to perform operations based on specific conditions, to modify related records
or restrict certain operations from happening.
• You can use triggers to execute SOQL and DML or calling custom Apex methods.
• Use triggers to perform tasks that can‟t be done by using the point-and-click tools in the Salesforce user
interface.
• Triggers are active by default when created. Salesforce automatically fires active triggers when the
specified database events occur.
Apex Triggers - Introduction
When to use salesforce triggers?
• We should use triggers to perform tasks that can‘t be done by using the point-and-click tools in
the Salesforce user interface.
• For example, if validating a field value or updating a field on a record, use validation rules
and workflow rules instead.
Trigger Syntax:
A trigger definition starts with the trigger keyword. It is then followed by the name of the trigger,
the Salesforce object that the trigger is associated with, and the conditions under which it fires.
code_block
}
Apex Triggers - Introduction
Here is a list of trigger events in salesforce. We can specify multiple trigger events in a comma-
separated list.
Apex Triggers - Introduction
Types of Triggers:
1. Before triggers are used to update or validate record values before they‟re saved to the database.
2. 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.
• All triggers define implicit variables that allow developers to access run-time context.
isBefore Returns true if this trigger was fired before any record was saved.
isAfter Returns true if this trigger was fired after all records were saved.
Returns true if this trigger was fired due to an insert operation, from the
isInsert
Salesforce user interface, Apex, or the API.
Returns true if this trigger was fired due to an update operation, from the
isUpdate
Salesforce user interface, Apex, or the API.
Returns true if this trigger was fired due to a delete operation, from the
isDelete
Salesforce user interface, Apex, or the API.
Context
Usage
Variable
Returns true if this trigger was fired after a record is recovered from the Recycle Bin.
isUndelete This recovery can occur after an undelete operation from the Salesforce user interface,
Apex, or the API.
Returns a list of the new versions of the sObject records.
new This sObject list is only available in insert, update, and undelete triggers, and the
records can only be modified in before triggers.
Returns a list of the old versions of the sObject records.
old
This sObject list is only available in update and delete triggers.
size The total number of records in a trigger invocation, both old and new.
if (Trigger.isInsert) {
if (Trigger.isBefore) {
TeacherTrigger.beforeInsert(Trigger.new); } } }
Class for Trigger:
public class TeacherTrigger {
public static void beforeInsert(List<Teacher__c> newList) {
for(Teacher__c a: newList) {
if(a.Teacher_Name__c=='Teacher5')
{ a.Experience__c = 5; }
else { a.Experience__c = 0; } } } }
Apex Triggers - Introduction
if (Trigger.isInsert) {
if (Trigger.isBefore) {
TeacherTrigger.beforeInsert(Trigger.new);
else if (Trigger.isAfter) {
TeacherTrigger.afterInsert(Trigger.new);
} } }
Apex Triggers - Introduction
Before Insert vs After Insert: Class for Trigger
public class TeacherTrigger {
public static void beforeInsert(List<Teacher__c> newList) {
for(Teacher__c a: newList) {
if(a.Teacher_Name__c=='Teacher5')
{
a.Experience__c = 5; }
else
{ a.Experience__c = 0; } } }
public static void afterInsert(List<Teacher__c> newList) {
Branch__c br = new Branch__c(Branch_Name__c='New Branch');
insert br; } }
Apex Triggers - Bulk Apex Triggers
Bulk Trigger Design Patterns:
• When you use bulk design patterns, your triggers have better performance, consume less server
resources, and are less likely to exceed platform limits.
• The 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.
• The following sections demonstrate the main ways of bulkifying your Apex code in triggers:
2. 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.
• The examples given are based on triggers and use the Trigger.new context variable.
Apex Triggers - Bulk Apex Triggers
Operating on Record Sets:
• Bulkified triggers operate on all sObjects in the trigger context.
• Typically, triggers operate on one record if the action that fired the trigger originates from the user interface.
• But if the origin of the action was bulk DML or the API, the trigger operates on a record set rather than one
record.
The following trigger (MyTriggerNotBulk) uses a for loop to iterate over all available sObjects.
for(Account a : Trigger.new) {
• The following example (SoqlTriggerBulk) a best practice for running SOQL queries.
• The SOQL query does the heavy lifting and is called once outside the main loop.
• Combining the two parts in the query results in the records we want in one
call: the accounts in this trigger with the related opportunities of each
account.
Apex Triggers - Bulk Apex Triggers
trigger SoqlTriggerBulk on Account(after update) {
for(Account a : acctsWithOpps) {
} }