Prevent Apex Trigger To Run Twice

Provide a static variable to check if trigger has already been called and prevent it to be called twice. In this case the static variable is called firstRun.

trigger AccountTrigger on Account (after delete, after insert, after undelete, after update, before delete, before insert, before update) {
    if (!System.isFuture() && !System.isBatch())
      AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);

      if(Trigger.isUpdate && Trigger.isBefore){
          handler.OnBeforeUpdate(Trigger.old,, Trigger.newMap);
      else if(Trigger.isUpdate && Trigger.isAfter){
        handler.OnAfterUpdate(Trigger.old,, Trigger.newMap);
      else if(Trigger.isDelete && Trigger.isBefore){
        handler.OnBeforeDelete(Trigger.old, Trigger.oldMap);
public with sharing class AccountTriggerHandler {
 	public static boolean firstRun = true; 

	private Boolean m_isExecuting = false;
    private Integer batchSize = 0;

	public AccountTriggerHandler(boolean isExecuting, integer size) {
		this.m_isExecuting = isExecuting;
        this.batchSize = size;

	public void onBeforeUpdate(List<Account> oldAccounts, List<Account> updatedAccounts, Map<Id, Account> accountMap){
		AccountUpdateActorId accountActorId = new AccountUpdateActorId();
		accountActorId.updateAccountId(oldAccounts, updatedAccounts, accountMap);
 		AccountSendEmailWhenOwnerChanges accountOwnerChangeNotification = new AccountSendEmailWhenOwnerChanges();
		accountOwnerChangeNotification.checkOwnerAndSendEmail(oldAccounts, updatedAccounts, accountMap);
	public void OnAfterUpdate(List<Account> oldAccounts, List<Account> updatedAccounts, Map<Id, Account> accountMap){
		UpdateHouseHoldReference houseReference = new UpdateHouseHoldReference();
		houseReference.updateAccountHouseholdReference(oldAccounts, updatedAccounts, accountMap);
	public void OnBeforeDelete(List<Account> deletedAccounts, Map<ID, Account> accountMap){
		ChangeAMIDAccountReferenceOnMerge changeAMIDAccounReference = new ChangeAMIDAccountReferenceOnMerge();
		changeAMIDAccounReference.changeAMIDAccountReferenceBeforeDelete(deletedAccounts, accountMap);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: