Trigger

Trigger

A trigger is the code that is executed before or after the record is updated or inserted
enable you to perform custom actions before or after events to records in Salesforce,
You can use triggers to do anything you can do in Apex, including executing SOQL and DML or calling custom Apex methods
The records that are fired in the after trigger are read-only.

Context variables 

  • 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

Best practice

  1. One trigger per object
  2. Logic-less Triggers
  3. Code coverage 100%
  4. Handle recursion
    1. public class checkRecursive {
           Public static Boolean firstcall=false;
      }
    2. Trigger feedback on contact (after update) {
      
      if(!checkRecursive.firstcall) {
             checkRecursive.firstcall = true;
             Id conId;
             for(contact c:trigger.new){
                 conId=c.Id;
             }
             Contact con=[select id, name from contact where id!=:conId limit1];
             con.email=‘test@gmail.com’;
             Update con;
      }}
 

Trigger events in salesforce

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete

Differences between Trigger and Workflow

  •  Unlike trigger, Workflow is an automated process that fires an action based upon evaluation criteria and rule criteria. 

  • We Can not edit an apex trigger/ apex class in the production environment.
  •  At least 75% of test coverage your trigger Apex code is required to deploy it to production.
  • We can call a future method from a trigger only if it is marked callout=true.
  • We can not make a callout from the trigger. But we can call a future method from trigger which in turn makes a callout.

  •   example: 

No comments:

Powered by Blogger.