Salesforce Best Practice Development Trigger

Apex Trigger Framework

Code Example Salesforce Apex Trigger

trigger AccountTrigger on Account (before insert, after insert, after update) {
    try {
        System.debug(LoggingLevel.DEBUG, '### UserInfo.getUserId(): ' + UserInfo.getUserId());
        System.debug(LoggingLevel.DEBUG, '### dateTime.now(): ' + dateTime.now());

        System.debug('Trigger.newMap: ' + Trigger.new);

        if(Trigger.isBefore) {
            if (Trigger.isInsert) {
                System.debug(LoggingLevel.DEBUG, '### BeforeInsert');
                AccountTriggerHandler.handleTrigger(Trigger.old, Trigger.oldMap, Trigger.new, Trigger.newMap, Trigger.operationType);
            } /*else if(Trigger.isUpdate) {
                System.debug(LoggingLevel.DEBUG, '### BeforeUpdate');

            } else if(Trigger.isDelete) {
                System.debug(LoggingLevel.DEBUG, '### BeforeDelete');

            }*/
        } else if(Trigger.isAfter) {
            if(Trigger.isInsert) {
                System.debug(LoggingLevel.DEBUG, '### AfterInsert ');
                AccountTriggerHandler.handleTrigger(Trigger.old, Trigger.oldMap, Trigger.new, Trigger.newMap, Trigger.operationType);
            } else if(Trigger.isUpdate) {
                System.debug(LoggingLevel.DEBUG, '### AfterUpdate');
                AccountTriggerHandler.handleTrigger(Trigger.old, Trigger.oldMap, Trigger.new, Trigger.newMap, Trigger.operationType);
            }/* else if(Trigger.isDelete) {
                System.debug(LoggingLevel.DEBUG, '### AfterDelete');
            } else if(Trigger.isUndelete) {
                System.debug(LoggingLevel.DEBUG, '### AfterUndelete');
            }*/
        }
    } catch(Exception e) {
        String errorMessage = 'Eccezione: ' + e.getMessage() + '\r\nLinea eccezione: ' + e.getLineNumber() + '\r\nStacktrace:\r\n' + e.getStackTraceString();
        System.debug(LoggingLevel.ERROR, '### ' + errorMessage);
        Utils.sendMailWRSupport('ERROR AccountTrigger', errorMessage, '');
    }
}

Code Example Salesforce Apex Trigger Handler

/**
 * Handler class for AccountTrigger
 * 
 * @author xxx
 * @version 1.0
 * @description AccountTrigger Handler
 * @testedIn 
 * @uses  Utils
 * @history
 * YYYY-MM-GG: xxx
 */
public with sharing class AccountTriggerHandler {

    public static Map<String, Schema.RecordTypeInfo> recordTypeMap = Utils.getSObjectTypeRecordTypeMap('Account');

    /**
     * method called by trigger
     *
     * @param oldRecords    list of the old versions of the sObject records
     * @param oldRecordsMap map of the old versions of the sObject records
     * @param newRecords    list of the new versions of the sObject records
     * @param newRecordsMap map of the new versions of the sObject records
     * @param triggerEvent  trigger context
     */
    public static void handleTrigger(List<Account> oldRecords, Map<Id, Account> oldRecordsMap,
                                        List<Account> newRecords, Map<Id, Account> newRecordsMap, System.TriggerOperation triggerEvent ) {

        System.debug('#### triggerEvent : ' + triggerEvent);
        switch on triggerEvent {

            when BEFORE_INSERT {

                for(Account account : newRecords){
                    setRecordTypeId(account);
                }
                
                System.debug('AccountTriggerHandler.onBeforeInsert - END');
            }
            when AFTER_INSERT {

                for(Account account : newRecords){        
                    updateMethod(account);
                }

                System.debug('AccountTriggerHandler.onAfterInsert - END');
            }
            when AFTER_UPDATE {
                updateAddress(oldRecordsMap, newRecordsMap);
            }
            when else {
                //do nothing for AFTER_UNDELETE, BEFORE_DELETE, or BEFORE_UPDATE
            }
        }
    }

    /**
     * set the recordType Id of account
     *
     * @param account Account record of wich is needed to set recordTypeId
     */
    public static void setRecordTypeId(Account account){

        if(recordTypeMap.containsKey(account.RecordTypeDeveloperName__c)){

            account.recordTypeId = recordTypeMap.get(account.RecordTypeDeveloperName__c).getRecordTypeId();

        }
    }

    public static void updateMethod(Account accounts){

        String idRTBrand = Settings__c.getInstance().IdRTAccountBrand__c;
        String RTStoreDirect = Settings__c.getInstance().IdRTStoreDirectAccount__c;
        String RTStoreAffiliated = Settings__c.getInstance().IdRTStoreAffiliatedAccount__c;


        if(accounts.recordTypeId == RTStoreDirect || accounts.RecordTypeId == RTStoreAffiliated){
            String storeBrand =  accounts.Brand__c;

            try{
                Account accTemp = [SELECT Id, CounterStoreNumber__c, BrandCode__c FROM Account WHERE RecordTypeId = :idRTBrand AND Id = :storeBrand LIMIT 1];

                Integer temp = Integer.valueOf(accTemp.CounterStoreNumber__c + 1);
                String tempSTR = (String.ValueOf(temp)).leftPad(5,'0');

                accTemp.CounterStoreNumber__c = temp;
                update accTemp;

                String codiceUnivocoPuntoVendita = '';
                
                codiceUnivocoPuntoVendita += accTemp.BrandCode__c.toUpperCase();
                codiceUnivocoPuntoVendita += tempSTR;

                Account accountToUpdate = new Account();
                accountToUpdate.Id = accounts.Id;
                accountToUpdate.CodiceUnivocoPuntoVendita__c = codiceUnivocoPuntoVendita;
                update accountToUpdate;
            }
            catch(Exception e){
                System.debug('#### ERRORE: ' + e.getMessage());
                String labelError = Label.Fill_all_the_Mandatory_Fields_for_Store;
                accounts.addError(labelError);
            }
        }
    }

    public static void updateAddress(Map<Id, Account> oldRecordsMap, Map<Id, Account> newRecordsMap) {
        System.debug('#### update address');

        Set<Id> accIds = new Set<Id>();
        for(Account a : newRecordsMap.values()) {
            System.debug('#### a.shippingaddress : ' + a.ShippingCity);
            if(a.ShippingCity != oldRecordsMap.get(a.Id).ShippingCity || 
               a.ShippingCountryCode != oldRecordsMap.get(a.Id).ShippingCountryCode ||
               a.ShippingPostalCode != oldRecordsMap.get(a.Id).ShippingPostalCode || 
               a.ShippingStateCode != oldRecordsMap.get(a.Id).ShippingStateCode || 
               a.ShippingStreet != oldRecordsMap.get(a.Id).ShippingStreet /*|| 
               a.Service_Territory_Merchandise__c != oldRecordsMap.get(a.Id).Service_Territory_Merchandise__c || 
               a.Service_Territory_Promoting__c != oldRecordsMap.get(a.Id).Service_Territory_Promoting__c || 
               a.Service_Territory_Retail__c != oldRecordsMap.get(a.Id).Service_Territory_Retail__c*/) {

                System.debug('#### address changed');
                accIds.add(a.Id);
            }
        }

        if(!accIds.isEmpty()) {
            System.debug('#### update wo address');
            List<WorkOrder> woUpdate = new List<WorkOrder>();
            Map<Id, WorkOrder> woMap = new Map<Id, WorkOrder>([SELECT Id, AccountId, City, CountryCode, PostalCode, StateCode, Street, ServiceTerritoryId, BusinessUnit__c 
                                                                FROM WorkOrder WHERE AccountId IN : accIds]);
            for(WorkOrder wo : woMap.values()) {
                Account a = newRecordsMap.get(wo.AccountId);
                if(a.ShippingCity != oldRecordsMap.get(a.Id).ShippingCity || 
                   a.ShippingCountryCode != oldRecordsMap.get(a.Id).ShippingCountryCode ||
                   a.ShippingPostalCode != oldRecordsMap.get(a.Id).ShippingPostalCode || 
                   a.ShippingStateCode != oldRecordsMap.get(a.Id).ShippingStateCode || 
                   a.ShippingStreet != oldRecordsMap.get(a.Id).ShippingStreet) {

                    wo.City = a.ShippingCity;
                    wo.CountryCode = a.ShippingCountryCode;
                    wo.PostalCode = a.ShippingPostalCode;
                    wo.StateCode = a.ShippingStateCode;
                    wo.Street = a.ShippingStreet;
                }

                if(a.Service_Territory_Merchandise__c != oldRecordsMap.get(a.Id).Service_Territory_Merchandise__c || 
                   a.Service_Territory_Promoting__c != oldRecordsMap.get(a.Id).Service_Territory_Promoting__c || 
                   a.Service_Territory_Retail__c != oldRecordsMap.get(a.Id).Service_Territory_Retail__c) {

                    String territory;
                    switch on wo.BusinessUnit__c {
                        when 'MerchServices' {
                            territory = a.Service_Territory_Merchandise__c;
                        }
                        when 'Promoting & Events' {
                            territory = a.Service_Territory_Promoting__c;
                        }
                        when 'RetailServices' {
                            territory = a.Service_Territory_Retail__c;
                        }
                        when 'BrandAmbassador' {
                            territory = a.Service_Territory_Merchandise__c;
                        }
                    }
                    wo.ServiceTerritoryId = territory;
                }
                woUpdate.add(wo);
            }

            if(woUpdate.size()>0){
                try {
                    system.debug('### (update) woUpdate: ' + woUpdate);
                    update woUpdate;
                } catch(Exception e) {
                    String errorMessage = 'Metodo AccountTriggerHandler()\r\n\r\nEccezione: ' + e.getMessage() + '\r\nLinea eccezione: ' + e.getLineNumber() + '\r\nStacktrace:\r\n' + e.getStackTraceString();
                    System.debug(LoggingLevel.ERROR, '### ' + errorMessage);
                    Utils.sendMailWRSupport('ERROR AccountTriggerHandler.updateAddress', errorMessage, '');
                }
            }

            System.debug('#### update sa address');
            List<ServiceAppointment> saUpdate = new List<ServiceAppointment>();
            Map<Id, ServiceAppointment> saMap = new Map<Id, ServiceAppointment>([SELECT Id, AccountId, City, CountryCode, PostalCode, StateCode, Street 
                                                                                 FROM ServiceAppointment WHERE AccountId IN : accIds]);

            for(ServiceAppointment sa : saMap.values()) {
                Account a = newRecordsMap.get(sa.AccountId);
                if(a.ShippingCity != oldRecordsMap.get(a.Id).ShippingCity || 
                   a.ShippingCountryCode != oldRecordsMap.get(a.Id).ShippingCountryCode ||
                   a.ShippingPostalCode != oldRecordsMap.get(a.Id).ShippingPostalCode || 
                   a.ShippingStateCode != oldRecordsMap.get(a.Id).ShippingStateCode || 
                   a.ShippingStreet != oldRecordsMap.get(a.Id).ShippingStreet) {

                    sa.City = a.ShippingCity;
                    sa.CountryCode = a.ShippingCountryCode;
                    sa.PostalCode = a.ShippingPostalCode;
                    sa.StateCode = a.ShippingStateCode;
                    sa.Street = a.ShippingStreet;
                }

                if(a.Service_Territory_Merchandise__c != oldRecordsMap.get(a.Id).Service_Territory_Merchandise__c || 
                   a.Service_Territory_Promoting__c != oldRecordsMap.get(a.Id).Service_Territory_Promoting__c || 
                   a.Service_Territory_Retail__c != oldRecordsMap.get(a.Id).Service_Territory_Retail__c) {

                    String territory;
                    switch on sa.BusinessUnit__c {
                        when 'MerchServices' {
                            territory = a.Service_Territory_Merchandise__c;
                        }
                        when 'Promoting & Events' {
                            territory = a.Service_Territory_Promoting__c;
                        }
                        when 'RetailServices' {
                            territory = a.Service_Territory_Retail__c;
                        }
                        when 'BrandAmbassador' {
                            territory = a.Service_Territory_Merchandise__c;
                        }
                    }
                    sa.ServiceTerritoryId = territory;
                }
                saUpdate.add(sa);
            }

            if(saUpdate.size()>0){
                try {
                    system.debug('### (update) saUpdate: ' + saUpdate);
                    update saUpdate; 
                } catch(Exception e) {
                    String errorMessage = 'Metodo AccountTriggerHandler()\r\n\r\nEccezione: ' + e.getMessage() + '\r\nLinea eccezione: ' + e.getLineNumber() + '\r\nStacktrace:\r\n' + e.getStackTraceString();
                    System.debug(LoggingLevel.ERROR, '### ' + errorMessage);
                    Utils.sendMailWRSupport('ERROR AccountTriggerHandler.updateAddress', errorMessage, '');
                }
            }
        }
    }
}