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
hanifa fatimahanifa fatima 

How to write a delete trigger when deleting the last child contact of an Account

trigger DeletingChildRecor on Account (Before delete) {
    Set<Id> s=new Set<Id>();
    for(Account a:Trigger.old)
    {
    System.debug('Adding ids');
        s.add(a.id);
    }
    list<contact> ls=[select id,name from contact where contact.accountid=:s];
    system.debug('About to Enter');
    if(Trigger.isDelete)
    {
    system.debug('Entered');
      if(ls.size()==1)
      {
          system.debug('Cant DELETE');
      }
          
  }
}

Here the trigger should fire when we delete the last child record of an account, it should throw an error saying that the last child cannot be be deleted.
Raj VakatiRaj Vakati
MOve trigger into the contact ..  try this code and bulkify it please
 
trigger DeletingChildRecor on Contact (Before delete) {
    Set<Id> s=new Set<Id>();
    for(Contact a:Trigger.old)
    {
List<Contact> cons = [Select Id from Contact where AccounId =:a.AccountId] ; 
	if(ls.size()==1)
      {
        a.addError('Cannt delete ');	
		
    }

       
          
  }
}

 
Steven NsubugaSteven Nsubuga
Try this
trigger DeletingChildRecor on Contact (Before delete) {
    
    Map<Id, List<Contact>> acctContacts = new Map<Id, List<Contact>>();
    
    for(Contact c:Trigger.old)
    {
        if (!acctContacts.keyset().contains(c.AccountId)) { System.debug('if 1');
            acctContacts.put(c.AccountId, new List<contact>());
        }
        List<Contact> contacts = acctContacts.get(c.AccountId);
        contacts.add(c);
        acctContacts.put(c.AccountId, contacts);
    }
    List<AggregateResult> ars = [select AccountId,count(id) from Contact where accountid IN:acctContacts.keyset() AND Id NOT IN:Trigger.oldMap.keyset() group by AccountId];

    Map<String, Integer> acctContactStats = new Map<String, Integer>();
    for (AggregateResult ar : ars) {
        
        Integer cc = Integer.valueOf(ar.get('expr0'));
        acctContactStats.put(String.valueOf(ar.get('AccountId').toString()), cc);
    }
    
    for(Id accountId : acctContacts.keyset()) {
        if (acctContacts.get(accountId).size() >= 1 && (acctContactStats.get(accountId)== 0 || acctContactStats.get(accountId)== null)) {
            
            // do not allow the first contact in the list to be deleted
            Trigger.oldMap.get(acctContacts.get(accountId)[0].Id).addError('Last account Contact, cannot be deleted');
        }
    }
}

 
Niraj Kr SinghNiraj Kr Singh
Hi Hanifa fatima,

You are doing event on contact so your trigger should be on that object "Contact".

And your trigger should be like this:
trigger DeletingChildRecor on Contact (before delete) {
    if(trigger.isBefore && trigger.isDelete) {
        Map<Id, List<Contact>> mapAccIdsVsContacts = new Map<Id, List<Contact>>();
        //All account
        for(Contact objCon : Trigger.old){
            if(mapAccIdsVsContacts.containsKey(objCon.AccountId)) {
                mapAccIdsVsContacts.get(objCon.AccountId).add(objCon);
            }
            else {
                mapAccIdsVsContacts.put(objCon.AccountId, new List<Contact>{objCon});
            }
            //setAccIds.add(objCon.id);
        }
        
        List<Contact> existingContacts = [SELECT Id, Name, AccountId FROM Contact WHERE AccountId IN: mapAccIdsVsContacts.keySet()];
        
        if(existingContacts != null) {
            for(Contact objCon : existingContacts) {
                if(mapAccIdsVsContacts.get(objCon.AccountId).size() == 1) {
                    objCon.addError('Sorry you can not delete. Account should have have atleast one contact');
                }
            }
        }
    }
}

Let me know if solved your problem.

Thanks
Niraj