Created
November 1, 2019 10:14
-
-
Save amitastreait/be73072f95794f39e95dd0b0e4bb537a to your computer and use it in GitHub Desktop.
All About Trigger Handler & Helper in #Salesforce #ApexTrigger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| trigger AccountTrigger on Account (before delete) { | |
| if ( Trigger.IsBefore && Trigger.isDelete ) { | |
| AccountTriggerHandler.handleBeforeDelete( Trigger.Old, Trigger.oldMap ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class AccountTriggerHandler { | |
| public static void handleBeforeDelete(List<Account> oldAccountList, Map<Id, Account> oldAccountMap) { | |
| /* | |
| * AccountTrigger => Handler AccountTriggerHandler | |
| * | |
| */ | |
| /* | |
| * Trigger.old => List<sObject> => List<Account> | |
| * Trigger.oldMap => Map<id, sobject> => Map<Id, Account> | |
| * keySet() => Set<Keys> => Set<id> => Set<AccountId> | |
| */ | |
| Set<Id> accountIdsSet = oldAccountMap.keySet(); | |
| List<Opportunity> opportunityList = [ | |
| Select Id, Name, StageName, AccountId | |
| From Opportunity | |
| Where AccountId IN : accountIdsSet | |
| AND IsWon = true | |
| ]; | |
| Map<Id, Opportunity> opportunitiesMap = new Map<id,Opportunity>(); | |
| // Key -> AccountId, Value -> Opportunity | |
| /* Approach 1 Using List | |
| for (Account acc : oldAccountList) { | |
| for ( Opportunity opp : opportunityList) { | |
| if ( acc.Id == opp.AccountId) { | |
| acc.addError('You can not delete the Account which have Closed Won Opportunities! Please Contact your admin'); | |
| } | |
| } | |
| } | |
| */ | |
| /* Approach 2 Usin Map */ | |
| for ( Opportunity opp : opportunityList) { | |
| if ( !opportunitiesMap.containsKey(opp.AccountId) ) { | |
| opportunitiesMap.put(opp.AccountId, opp); | |
| } | |
| } | |
| for (Account acc : oldAccountList) { | |
| if( opportunitiesMap.containsKey(acc.Id) ) { | |
| acc.addError('You can not delete the Account which have Closed Won Opportunities! Please Contact your admin'); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment