+ Start a Discussion
Mike Tol 1Mike Tol 1 

Change the code to handler trigger

Hi. I have this trigger:
trigger preventAccountCreateOrUpdate on Account (before insert, before update) {
            for (Account a : Trigger.new) {
            if (a.type=='Prospect') {
              a.addError('You can not create or update this record.');
            }
          }
        }
How can I change the code to handler trigger that I have Account Trigger Handler Class and Account Trigger?
 
Best Answer chosen by Mike Tol 1
MagulanDuraipandianMagulanDuraipandian
Mike,
Trigger:
trigger preventAccountCreateOrUpdate on Account (before insert, before update) {
    if ( trigger.isBefore ) {
        if ( trigger.isInsert ) {
            AccountTriggerHandler.onBeforeInsert(trigger.new);
        } else if ( trigger.isUpdate ) {
            AccountTriggerHandler.onBeforeUpdate(trigger.new, trigger.oldMap);
        } 
    } 
}

Handler Class:
public class AccountTriggerHandler {
        
    public static void onBeforeInsert(List<Account> AccountList) {
        validateAccounts(AccountList, null );
    }

    public static void onBeforeUpdate(List<Account> AccountList, Map<Id, Account> mapAccountOld) {
        validateAccounts(AccountList, mapAccountOld );
    }

    static void validateAccounts(List<Account> AccountList, Map<Id, Account> mapAccountOld) {
    
        for (Account a : AccountList) {
            if (a.type=='Prospect') {
                a.addError('You can not create or update this record.');
            }
        }
        
    }
    
}

You can find syntax here: https://www.infallibletechie.com/2014/05/trigger-handler-controller-in-salesforce.html

All Answers

MagulanDuraipandianMagulanDuraipandian
Mike,
Trigger:
trigger preventAccountCreateOrUpdate on Account (before insert, before update) {
    if ( trigger.isBefore ) {
        if ( trigger.isInsert ) {
            AccountTriggerHandler.onBeforeInsert(trigger.new);
        } else if ( trigger.isUpdate ) {
            AccountTriggerHandler.onBeforeUpdate(trigger.new, trigger.oldMap);
        } 
    } 
}

Handler Class:
public class AccountTriggerHandler {
        
    public static void onBeforeInsert(List<Account> AccountList) {
        validateAccounts(AccountList, null );
    }

    public static void onBeforeUpdate(List<Account> AccountList, Map<Id, Account> mapAccountOld) {
        validateAccounts(AccountList, mapAccountOld );
    }

    static void validateAccounts(List<Account> AccountList, Map<Id, Account> mapAccountOld) {
    
        for (Account a : AccountList) {
            if (a.type=='Prospect') {
                a.addError('You can not create or update this record.');
            }
        }
        
    }
    
}

You can find syntax here: https://www.infallibletechie.com/2014/05/trigger-handler-controller-in-salesforce.html
This was selected as the best answer
Mike Tol 1Mike Tol 1
thank you very much!!!