Tuesday, December 20, 2022

Triggers

Triggers:

 A trigger is an apex code that performs validations while performing DML operations. 

* Validations: For filtering the data (To make proper data insert otherwise we will throw an error message through validations). 

* Trigger runs in System Mode by default unless we hand over  to a class decorated as 'with sharing'. 

* By default triggers will run in a batch of 200 records. 200 records for one trigger invocation, even in case of Bulk API.

* SOSL cannot be used in Triggers.

 

*Workflow automates on insert, update.
*Trigger automates on all the DML statements including delete and undelete operations except 
  upsert and merge.
*A workflow can update the fields of the current object.
*Trigger can perform cross object referencing.
*Triggers execute only at run-time.
Bulk Triggers:
*All triggers are bulk triggers by default and can process multiple records at a time.
*Triggers can handle both single record updates and bulk operations.
1.Data import 2.Force.com Bulk API calls 3.Mass Actions 4.Recursive Apex Methods
*A Trigger can works in two modes
1.) Before: works before executing DML statements. (Before saving into model)
2.) After: Works after executing DML statements. (After saving into model but not commit)
What are the Events in Triggers?
* no before undelete event for Triggers
* we should not use upsert and merge for the triggers
Detail Information for Trigger Events 
DML
Before State (Old)
After State (New)
Insert
No
yes
Update
Yes
Yes
Upsert
Never use in Triggers
Never use in Triggers
Delete
Yes
No
Undelete
No
Yes
Merge
Never use in Triggers
Never use in Triggers

*APEX provides Trigger Context Variables, Which holds run-time information used by the trigger.

Trigger Context Variables which generates Boolean values:
Trigger.isBefore
Returns ‘T’ if the triggers is executing in before mode
Trigger.isAfter
Returns ‘T’ if the triggers is executing in after mode
Trigger.isInsert
Returns ‘T’ if the DML operation is in insert mode
Trigger.isUpdate
Returns ‘T’ if the DML operation is in update mode
Trigger.isDelete
Returns ‘T’ if the DML operation is in delete mode
Trigger.isUndelete
Returns ‘T’ if the DML operation is in undelete mode
‘is’ before name represents Boolean types i.e. either ‘T’ or ‘F’

 Trigger Context Variables which works for collection of records:
Trigger.new
Gives collection of records that represents the new state of sObject.
Trigger.old
Gives collection of records that represents the old state of sObject.
Trigger.newMap
A map of Id’s to the new version of sObject records.
Trigger.OldMap
A map of Id’s to the old version of sObject records.
Trigger.Size
Total number of records in a trigger invocation i.e. for both old & new.
Note:
new – Available for insert, update and undelete.
Old - Available for update and delete.
newMap – Available for before update, after insert & after update.


Syntax:
trigger <name> on <sObject name> (<events>) {
}

Examples:
--------------------------

trigger FirstInsert on Student__c (before insert) {
    List<Student__c> s_list = Trigger.new;
    for(Student__c s : s_list) {
        if(s.Name__c == 'Srinu') {
            s.addError('He is not a right candidate.');
        }
    }    
}
trigger FirstUpdate on Student__c (before update) {
    List <Student__c> s_list = Trigger.new;
    for(Student__c s: s_list) {
        if(s.Name__c == 'Vasu') {
            s.addError('He is Good');
        }
    }
}
 trigger Multiple on Student__c (before insert,before update) {
    if(Trigger.isinsert) {//if is is inserting
        List<Student__c> s_list = Trigger.new;
        for(Student__c s:s_list) {
            if(s.Name__c == 'Srinu') {
                s.addError('This is Srinu');
            }
        }
    }    
    if(Trigger.isupdate) {//if it is updating
        List<Student__c> s_list = Trigger.new;
        for(Student__c s:s_list) {
            if(s.Name__c == 'Vasu') {
                s.addError('This is Vasu');
            }
        }  
    }
}
/*
If the same events occur in same block of code(i.e same trigger) then which has recently 
created that trigger will get fire

If same events occur in different triggers then which trigger is the oldest created 
date and time that trigger will get fire 

If there are multiple events in one block of code and diff number of events in another block 
of code but the error conditions are same then recently created trigger error msg only fire
*/ 
 
Triggers and Order of Execution:

*When we save a record with insert/update statement, salesforce performs the following event in order:

Note: Before Salesforce executes these events on the server browser runs the JavaScript validations.

1. Loads the original record form database/ initializes for an insert/update statement.
2. Loads new records field values from the request and overwrites the old values.
3. Executes all the before triggers.
4. Run most system validation steps [Required field have not null value].
5. Saves record to database, but does not do commit yet.
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 record again.
11. If record updated with workflow field values, fires before and after triggers one more time.
12. Executes escalation rules.
13. If record contains roll-up summary field/ is part of cross-object workflow, performs calculations and updates roll-up summary field in parent record then saves.
14. If parent record updated, grand-parent record contains roll-up summary field, perform calculations and updates roll-up summary field in parent record then saves.
15. Executes criteria based sharing evaluation.
16. Commit all the DML operations to the database.
17. Executes post commit logic, such as send email.
Note: During recursive save, sales force skips step (7) – (14).

Interview Questions:

Q. What operations that don't invoke triggers?
A. Triggers only invoked by the DML operations that are initiated/processed by Java Application server.
 *Examples that operations don't invoke by the triggers:
  1. Cascading delete (Bulk delete).
  2. Cascading updates of child records.
  3. Mass Campaign status changes.
4. Mass division transfers.
5. Mass address updates.
6. Mass approval request transfers.
7. Mass email actions.
8. Modifying custom field data types.
9. Renaming or replacing pick-lists.
10. Managing price books.
11. Changing a user's default division with the transfer division option checked.
12. Changes to the following objects:
     i. Brand Template 
     ii. MassEmail
     iii. Template Folder
13. Update account triggers don't fire before or after a business account record type is changed to person account (or a person account record type is changed to business account.)
Note: 
    Inserts, updates, and deletes on person accounts fire account triggers, not contact triggers.
    Before triggers associated with the following operations are only fired during lead conversion if validation and triggers for lead conversion are enabled in the organization:
14. insert of accounts, contacts, and opportunities.
15. update of accounts and contacts.

Q. Fields that can not be updated by triggers?
A. 1. Task.isclosed 2. Opportunity.amount* 3. Case.isclosed 4. Opportunity.iswon
     5. Solution.isReviewed 6. Contact.activatedDate 7. Opportunity.isclosed
     Note: Above field values set during save operation.
 Q. How to avoid recursive triggers?
 A. Using static Boolean variable we can control recursive triggers.
 Q. Handling Governor limits through triggers?
Scenarios  
* Whenever Opportunity stagename fieldset to 'Closed one',
 a new record has created in patient object
* Try to access info. form sObj for which don't have permissions for user using trigger

No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...