[SalesForce] Trigger to create new event after insert/update creating dupes

I have a trigger that should create a new event after insert or after update of a custom object called Handoff, but only if a custom field (Status) of that new record = "Delivered"

The after insert portion works fine, but the after update portion seems to always create duplicate events (two, to be precise).

I can't quite seem to find where it's going wrong within the trigger… any ideas?

trigger CreateEventAfterHandoff on Handoff__c (after insert, after update) {

List<Event> lstNewEvents = new List<Event>();

for (Handoff__c eve : Trigger.new) {

    if (Trigger.isUpdate) {

        if (eve.Status__c != Trigger.oldMap.get(eve.Id).Status__c) { 

        // Field has been changed! 

            if (eve.Status__c == 'Delivered') {

                Event e         = new Event();

                e.Event_Type__c     = eve.Event_Type__c;
                e.Meeting_Type__c   = eve.Meeting_Type__c;
                e.StartDateTime     = eve.Meeting_Time_Start__c;
                e.EndDateTime       = eve.Meeting_Time_Stop__c;
                e.Subject           = eve.Name;
                e.WhoId             = eve.Lead__c;
                e.OwnerId           = eve.User__c;
                e.Handoff_ID__c     = eve.Id;

                lstNewEvents.add(e);

            }           

        }

    } else if (Trigger.isInsert) {

        if (eve.Status__c == 'Delivered') {

            Event e         = new Event();

            e.Event_Type__c     = eve.Event_Type__c;
            e.Meeting_Type__c   = eve.Meeting_Type__c;
            e.StartDateTime     = eve.Meeting_Time_Start__c;
            e.EndDateTime       = eve.Meeting_Time_Stop__c;
            e.Subject           = eve.Name;
            e.WhoId             = eve.Lead__c;
            e.OwnerId           = eve.User__c;
            e.Handoff_ID__c     = eve.Id;

            lstNewEvents.add(e);

        }

    }           

}

insert lstNewEvents;     

}

Best Answer

Most likely the cause is either

  1. You have a second trigger somewhere else in your code base on Handoff__c that in turn does a DML update on itself or
  2. You have a field update on Handoff__c via a workflow that will cause the after update trigger to be reinvoked.

You can resolve either of these by using the controlling recursive triggers recipe as shown in the SFDC doc here or here in Help doc. You may also be able to control it by tighter if statements to avoid creating the Events even if invoked twice.

This SFSE post addresses workflows and updates of greater than 200 records

Lastly, examine your debug log to see where the after update trigger on Handoff__c gets reinvoked, this may provide additional insight

Related Topic