• Abeer @ Cloud3
  • NEWBIE
  • 0 Points
  • Member since 2011

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I have an Apex trigger that writes "Lead Status History" to a custom object I've made called "Lead_Status_History__c". It fires whenever the lead status changes on a lead. The problem I am having is that the trigger is firing twice on a specific Lead Status.
 
I believe the reason why it is firing twice on this specific lead status is because I have a workflow rule set up on the lead. When the lead status is changed to that specific status, it performs a field update on a date field on the lead, and I believe that this field update is causing my trigger to fire again.
 
To rehash the order of execution when it comes to triggers, I'll highlight the steps that are relevant to me:
 

1. The original record loads from the database or initializes for an insert operation
2. The new values load from the incoming request and overwrite the old values in the record buffer. The old values are saved in the old context variable for update triggers.
3. Before triggers run.
...
5. The record is saved to the database, but the record is not committed.
6. After triggers run.
...
8. Workflow rules execute. If field updates are specified, the record updates again, and before and after triggers for the update fire.
...
10. All data manipulation operations are committed to the database.


I believe step 8 is causing my trigger to fire again. Is there anyway to prevent triggers from doing a repeat action if step 8 causes your trigger to fire again?

Here is my apex trigger code:

Code:
trigger LeadStatusHistoryTrigger on Lead (before update) 
{
 // Declare a list of Lead_Status_History__c to be insertedin Salesforce
 List<Lead_Status_History__c> LeadStatusHistoryObjects = new List<Lead_Status_History__c>();
 
 // If the trigger is an update trigger insert all the new status changes
 if ( Trigger.isUpdate )
 {
  for ( Lead l_new: Trigger.new )
  {
    // Check to see if the status of the old and new lead values are the same.
    // If they are different then we create a new entry in the lead_status_history custom object
    if ( l_new.Status != Trigger.oldMap.get( l_new.Id ).Status )
    {
     LeadStatusHistoryObjects.add( new Lead_Status_History__c ( Lead__c = l_new.Id, Lead_Status_New__c = l_new.Status, Lead_Status_Old__c = Trigger.oldMap.get( l_new.Id ).Status ) ); 
    }
  }
  
  // After all the new Lead Status History items have been added, now insert them into Salesforce
  try
  {
   insert LeadStatusHistoryObjects;
  }
  catch (DmlException de)
  {
   for ( integer i = 0; i < de.getNumDml(); i++ )
   {
    System.debug('LeadStatusHistoryTrigger Error Inserting Lead Status History Objects: ' + de.getDmlMessage(i));
   } 
  }
  
 }
}


 

  • November 17, 2008
  • Like
  • 0