function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kaustubh chandratrekaustubh chandratre 

write a trigger to prevent account from deleting, if it has two or more contacts

AnkaiahAnkaiah (Salesforce Developers) 
Hi Kaustubh,

Refer the below link have solution.

https://salesforce.stackexchange.com/questions/329222/prevent-account-from-deleting-if-it-has-2-or-more-contacts

If this helps, Please mark it as best answer.

Thanks!!
AnkaiahAnkaiah (Salesforce Developers) 
Hi 

try with below code.
trigger AccountContactCheck on Account (before delete) {   
for (AggregateResult ar : [SELECT accountid, count(id)size  FROM contact where accountid in : Trigger.oldMap.keySet() GROUP BY accountid])
    if(((integer)ar.get('size'))>=2)
         trigger.oldMap.get((id)ar.get('accountid')).adderror('This account have more than 2 contacts you cant delete');         
}

If this helps, Please mark it as best answer.

Thanks!!
 
Mona KawaleMona Kawale
Hi @Kaustubh
Please check below code: 

If this helps, Please mark it as best answer.

Thanks!!
Apex Class
public class PreventAccfromDeletion2 {
 public static void mymethod(list<account> acclist){
     set<id> accids=new set<id>();
     for(account acc:acclist){
         accids.add(acc.id);
     }
     
     if(!accids.isempty()){
         map<id,account> newacc=new map<id,account>([select id, name,(Select id from contacts) from account where id=:accids]);
     
        if(!newacc.isempty()){
            for(Account acc:acclist){
                if(newacc.get(acc.id).contacts.size()>2)
                    acc.adderror('You cannot delete the account that having more than 2 contacts');
                }
            }
        }
        
    }


Trigger


trigger AccTriggerDuplicateAcc on Account (After insert, before update,before delete) { 
    if(trigger.isdelete && trigger.isbefore){
       PreventAccFromDeletion.myMethod(Trigger.old);
    }
}
Manukumar V BManukumar V B
Hi
Please check below code trigger AccountTrigger on Account (before Delete) {
           
        for(Account acc :[Select ID,Name ,(select AccountID,ID from Contacts) from Account where id in :Trigger.old]){
            
            if(acc.Contacts.Size()>=2){
                
            trigger.oldmap.get(acc.Id).addError(' Account : '+acc.Name+' has two or more related contacts so you can\'t delete account.');
          }
        }
             
    }
Prudhvi ChejarlaPrudhvi Chejarla
@mona That code not worked because In 13th line you missed the Open  flower Brocket in If function as well as you 2 more closed flower brockets
Junaid AnsariJunaid Ansari
Hi, check this out for easy and clean code.

public static void restrictAccountDelete(List<Account> listOfAccount){        
        Final Integer contactLimit = 2;
        
        Map<Id, Integer> MAP_OF_ACCID_WITH_NUM_CON = new Map<Id, Integer>();
        
        if(listOfAccount != null && listOfAccount.size() > 0 ){            
            for(Contact itrCon : [SELECT id, AccountId From Contact WHERE AccountId != null AND AccountId IN : listOfAccount]) {
                if(MAP_OF_ACCID_WITH_NUM_CON.containsKey(itrCon.AccountId)){
                    MAP_OF_ACCID_WITH_NUM_CON.put(itrCon.AccountId, MAP_OF_ACCID_WITH_NUM_CON.get(itrCon.AccountId)+1);
                }else{
                    MAP_OF_ACCID_WITH_NUM_CON.put(itrCon.AccountId, 1);
                }
            }
        
            for(Account itrAccount : listOfAccount){
                if(MAP_OF_ACCID_WITH_NUM_CON != null && MAP_OF_ACCID_WITH_NUM_CON.size() > 0 ){
                    if(MAP_OF_ACCID_WITH_NUM_CON.containsKey(itrAccount.Id) && MAP_OF_ACCID_WITH_NUM_CON.get(itrAccount.Id) >= contactLimit ){
                        itrAccount.addError('You can not delete this account because it have more than one contact');
                    }
                }
            }
            
        }
    }