1

I'll make this as simple as possible. I have a trigger on the contact object. It is to fire after insert or after update. If it's an insert operation I need to send a callout message saying essentially 'Contact created'. If it's an update operation I need to send a callout message saying 'Contact updated'. The problem is that there is a managed package installed that also has trigger on the contact object and it fires first. If the user creates a new contact record, the managed package trigger sets a field and then performs a DML update on the new record. What happens next is this fires my trigger as an 'AFTER UPDATE', then later as an 'AFTER INSERT'.

Why? How does my trigger know when first called(AFTER UPDATE) that this is actually an INSERT of a record?

Here's the edited debug log:

14:31:13.165 (429325994)|ENTERING_MANAGED_PKG|integrator_da
14:31:13.165 (429670005)|DML_BEGIN|[181]|Op:Update|Type:Contact|Rows:1
14:31:13.616 (616358875)|CODE_UNIT_STARTED|[EXTERNAL]|01q4C0000000JrB|Contacts on Contact trigger event AfterUpdate|__sfdc_trigger/Contacts
14:31:13.647 (647778607)|CODE_UNIT_STARTED|[EXTERNAL]|01q4C0000000JrB|Contacts on Contact trigger event AfterInsert|__sfdc_trigger/Contacts
1
  • a) trigger execution order is undefined 2) I would suggest keeping state on Contact (as to whether you have ever sent a Contact inserted message ; and 3) do this in an async transaction (future or queueable)
    – cropredy
    Commented Sep 8, 2018 at 2:16

1 Answer 1

1

To solve this problem, I'd recommend a static variable. Set it in the before insert trigger, and check it in your after update trigger. We can't control the order of triggers, but we can guarantee that all before triggers will execute before any after triggers do, so setting the variable beforehand should work as you expect.


public class ContactAPINotify {
  public static Boolean isInsert = false;
  ...
}

switch on Trigger.operationType {
  when BEFORE_INSERT {
    ContactAPINotify.isInsert = true;
  }
  when AFTER_INSERT {
    ContactAPINotify.callNewContactAPI(Trigger.new);
  }
  when AFTER_UPDATE {
    if(!ContactAPINotify.isInsert) {
      ContactAPINotify.callUpdatedContactAPI(Trigger.new);
    }
  }
}
2
  • This would work for pure inserts, but I would still have a problem with upserts. Some records are being inserted, others updated. I think I'm going to have to put a boolean field on the contacts object that tells me whether a particular record is new.
    – Jerry
    Commented Sep 10, 2018 at 15:55
  • @Jerry yes, this was only an example. If you need a more complicated scenario, a Set of ID values would probably assist you better.
    – sfdcfox
    Commented Sep 10, 2018 at 15:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .