Triggers in apex:
Trigger is Piece of code that is executes before and after a record is Inserted/Updated/Deleted from the force.com database. It Can be created on any custom or standard objects.
Triggers execute either “before” or “after” the event.and following are the events to be used in triggers:
1) before insert
2) before update
3) before delete
4) after insert
5) after update
6) after delete
7) after undelete
Use of before and after events:
“before” trigger can update or validate values before they are saved to the database.
“after” triggers can access field values that are set automatically (such as ID or lastUpdated fields) or to affect changes in other records (such as auditing or queued events)
Syntax :
Trigger on
Best Practice to write the trigger :
• Write one trigger (class) per object.
• Multiple triggers can be written on an object but not recommended.
• In case of multiple triggers order of execution cannot be controlled.
All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.
• isInsert
• isUpdate
• isDelete
• isBefore
• isAfter
• isUndelete
• New
• Old
• NewMap
• OldMap
• Size
• isExecuting
Trigger Example:
Ø In the Developer Console, click File | New | Apex Trigger.
Ø Enter HelloWorldTrigger for the trigger name, and then select Account for the sObject. Click Submit.
trigger ExampleTrigger on Account (before insert)
{
System.debug('Account inserted!');
}
Ø Alternately on the org go to Customize | Accounts | Triggers and create New Trigger.
Ø To test the trigger, create an account. Click Debug | Open Execute Anonymous Window.
Ø In the new window, add the following and then click Execute.
Account a = new Account(Name='Test Trigger');
insert a;
Ø Alternately on the org create an account from UI and check debug logs.
Trigger Context Variable Example:
• This example is a modified version of the ExampleTrigger trigger.
trigger ExampleTrigger on Account (before insert)
{
for(Account acc : Trigger.New)
{
acc.Description = 'New Account';
}
}
Ø Trigger.new is a list of sObjects
Ø The list can be iterated over in a for loop, or used as a bind variable in the IN clause of a SOQL query.
Bulk Triggers:
Ø In earlier example Trigger.new is a list of sObjects
Ø Why list?
o Because all triggers are considered to be bulk triggers and should be able to process multiple records at a time.
§ Remember triggers execute via API access or dataloader as well.
Ø Therefore Trigger.New contains all the records that were inserted in insert or update triggers.
Ø Trigger.Old provides the old version of sObjects before they were updated in update triggers, or a list of deleted sObjects in delete triggers.
More Trigger Context Variable Example
Ø Some other context variables return a Boolean value to indicate whether the trigger was fired due to an update or some other event. These variables are useful when a trigger combines multiple events. For example:
trigger ContextExampleTrigger on Account (before insert, after insert, after delete){
if (Trigger.isInsert) {
if (Trigger.isBefore) {
// Process before insert
} else if (Trigger.isAfter) {
// Process after insert
}
} else if (Trigger.isDelete) {
// Process after delete
}
}
Ø Write a trigger which will create related contact object automatically on creating an account:
trigger CreateContact on Account (after insert) {
if(Trigger.isInsert)
{
List listContacts = new List ();
for(Account acc :Trigger.new)
{
Contact cnt = new Contact(LastName = acc.Name, AccountId = acc.Id);
listContacts.add(cnt);
}
insert listContacts;
}
}
Ø Write a trigger which will create related contact object automatically on creating an account:
trigger CreateContact on Account (after insert) {
if(Trigger.isInsert)
{
CreateContactUtility.CreateContacts(Trigger.New);
}
}
Calling a class method from a trigger:
Public Class CreateContactUtility{
public static void CreateContacts(List lstAccounts)
{
system.debug('Account ::'+lstAccounts);
ListlstContacts = new List ();
if(lstAccounts.size()>0)
{
for(Account acc :lstAccounts)
{
Contact cnt = new Contact(LastName = acc.Name, AccountId = acc.Id);
lstContacts.add(cnt);
}
insert lstContacts;
}
}
}
Using Trigger Exceptions:
• addError() method:
trigger AccountDeletion on Account (before delete) {
// Prevent the deletion of accounts if they have related opportunities associated to that account.
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(
'can not delete the account with related opportunitues.');
}
}
How to disable trigger?
Ø Goto Setup, search for Apex Triggers in search box.
Ø On the Apex Triggers page, click Edit next to the AccountDeletion trigger.
Ø Deselect Is Active.
Ø Click Save.
Ø Done
What is Importance of bulkifying your triggers?
Ø A trigger can process anywhere from 1 to 200 records so all triggers should be written to accommodate bulk transactions.
Use Case :
Ø Each time a new opportunity is created, you would like to do some branding activity like send a free gift to your prospect. So create a task as soon as an opportunity is created.
Don’t write trigger like below:
// Remember that up to 200 records can be in Trigger.new
for (Opportunity opp : Trigger.new) {
Task t = new Task();
t.Name = 'Give your prospect a welcome gift';
t.WhatId = opp.Id;
insert t;
// You'll get an error after the 150th opp!
}
Right way of writing a trigger:
// insert DML should be performed once using a List outside for loop
List taskList = new List();
for (Opportunity opp : Trigger.new) {
Task t = new Task();
t.Name = 'Give your prospect a free t-shirt';
t.WhatId = opp.Id;
taskList.add(t);
}
insert taskList; // take note that this is outside the loop
Things to keep in ming while writing triggers:
Ø All triggers are considered to be bulk triggers and should be able to process multiple records at a time.
Ø All triggers run as System by default
o This means that triggers have access to objects and fields that the current user does not have
o You can override this using the with sharing keywords.
Ø Trigger code cannot contain static keyword.
Best Practices:
Ø Avoid DML statements inside (“FOR”) Loops.
Ø Use one trigger for each object
Ø Make sure you bulkify your apex code
Ø Minimize large data sets in your triggers
Order of Execution
1. System Validation Rules.
2. Executes all before triggers.
3. Custom Validation rules.
4. Executes all after triggers.
5. Executes assignment rules.
6. Executes auto-response rules.
7. Executes workflow rules.
8. If there are workflow field updates, updates the record again.
2. Executes all before triggers.
3. Custom Validation rules.
4. Executes all after triggers.
5. Executes assignment rules.
6. Executes auto-response rules.
7. Executes workflow rules.
8. If there are workflow field updates, updates the record again.
9. If the record was updated with workflow field updates, fires before and after triggers one more time. Custom validation rules are not run again.
10. Executes escalation rules.
11. 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.
12. If the parent record is updated, and a grand-parent 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. Grand-parent record goes through save procedure.
13. Executes Criteria Based Sharing evaluation.
14. Commits all DML operations to the database.
15. Executes post-commit logic. Ex: Sending email.
11. 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.
12. If the parent record is updated, and a grand-parent 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. Grand-parent record goes through save procedure.
13. Executes Criteria Based Sharing evaluation.
14. Commits all DML operations to the database.
15. Executes post-commit logic. Ex: Sending email.
Workflows: is process automation in salesforce using workflows we can do below tasks:
• Update field
• Assign Task
• Send Email
• Outbound Message
We can not do below tasks using workflows:
• Create other records
• Automatically create child records
• Complex calculations (Business logic)
• Calculate total revenue from child account
• Automatically submit records for approval
• Delete records
0 Comments