0

I have some logic which only can be run in trigger After Update(not after Insert). Here is the code:

trigger Contact on Contact (before insert, before update, after insert, after update,before delete, after delete ,after undelete) {
    System.debug('===================come into contact trigger===========');
    if (trigger.isAfter && trigger.isInsert){
        System.debug('=============== after insert');
    }
    if (trigger.isAfter && trigger.isUpdate){
        System.debug('=============== after update');
    }
}

when I do a simple insert of a contact(Not upsert just insert), on the debug log the '======after update' is shown.

From the document what my understand is that isUpdate is only returning true if the it is an actual update case https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htm

  • 4
    It is extremely common for an insert to fire off events which cause the record to be updated. Even a single Workflow Field Update would suffice. – Adrian Larson Aug 25 '17 at 22:53
  • @AdrianLarson You are quite right, after a bit of diving into the debug log, I figured out that the updated event is caused by a workflow that got run after the insert of the record. – bluecat Sep 5 '17 at 16:11
1

Trigger.isUpdate actually means that the current trigger is in an update mode. This can happen during insert as the result of a workflow rule, Process Builder flow, or another trigger.

In fact, I once wrote a trigger that needed Id values in Trigger.new and needed to write to field values in Trigger.new, thus prompting this solution:

trigger DoSomethingOnContact on Contact (after insert, before update) {
  if(Trigger.isInsert) {
    update Trigger.new.deepClone(true); // Preserve ID values
  } else {
    // Do stuff here
  }
}

Of course, if I'd written it today, if would have been more careful with error checking, but the point is that this trigger intentionally called itself recursively to avoid the situation where I didn't have a record Id to use in my logic.

  • yes! This update is caused by a workflow that run after the insert of the record. I have one more question regarding to the update process in this case: after insert trigger->workflow logic->update trigger. In the last update trigger, will trigger run in is own context? that is for example the "workflow logic" only change record1.property1 then in the update trigger the difference between trigger.new and trigger.old is only record1.property1. – bluecat Sep 5 '17 at 16:22
  • @bluecat Yes, that should be correct. Only the records that are updated are re-triggered. – sfdcfox Sep 5 '17 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.