Please refer the below code for prevention of deletion of accounts which have more than 2 contacts associated with them.
trigger preventDelete on Account (before delete) { // Get an aggregate Result per account i.e no of account associate with each Account in Trigger.Old List<AggregateResult> groupedResult = [SELECT AccountId,Count(Id)Cont FROM Contact where AccountId IN : Trigger.old group by AccountId ];
// Create a map of accountId and its associated Contacts Map<String,Integer> actToContact = new Map<String,Integer>();
for(AggregateResult ar: groupedResult){ // Type Cast is done as the returned values are of object Type. actToContact.put((String)ar.get('AccountId'), (Integer)ar.get('Cont')); }
// Add error for the accounts which have 2 or more contacts for(String actId : actToContact.keySet()){ if(actToContact.get(actId) > 2){ Trigger.oldMap.get(actId).addError('Cannot delete Account associated with multiple contacts'); } } }
Please mark it as the best answer if it solves the issue.
Please refer the below code for prevention of deletion of accounts which have more than 2 contacts associated with them.
trigger preventDelete on Account (before delete) {
// Get an aggregate Result per account i.e no of account associate with each Account in Trigger.Old
List<AggregateResult> groupedResult = [SELECT AccountId,Count(Id)Cont FROM Contact where AccountId IN : Trigger.old group by AccountId ];
// Create a map of accountId and its associated Contacts
Map<String,Integer> actToContact = new Map<String,Integer>();
for(AggregateResult ar: groupedResult){
// Type Cast is done as the returned values are of object Type.
actToContact.put((String)ar.get('AccountId'), (Integer)ar.get('Cont'));
}
// Add error for the accounts which have 2 or more contacts
for(String actId : actToContact.keySet()){
if(actToContact.get(actId) > 2){
Trigger.oldMap.get(actId).addError('Cannot delete Account associated with multiple contacts');
}
}
}
Please mark it as the best answer if it solves the issue.
Here is a trigger by which you can stop deletion of Account which is associated with more than 2 Contacts ---
------------------Trigger Part ---------------------
If you found this answer helpful then please mark it as best answer so it can help others.
Thanks
Ajay Dubedi