[SalesForce] Account that has related contacts should not be deleted

I need to write a trigger in which if an account that has related contacts and the user tries to delete that account it throws you an error..

trigger DoNotDeleteAccountHavingRelatedContact on Account (before insert, before update)  
{  
    List<Account> accList = new List<Account>();  
    Set<id> accIdSet = new Set<id>();  
    for(Account acc : Trigger.new)  
    {  
        accIdSet.add(acc.id);  
    }  

Map<Id,Contact> mapContacts = new Map<Id,Contact>([Select lastname,id,accountid 
                                        From Contact Where Accountid 
                                        IN : accIdSet]);

for(Account acc : Trigger.new)
{
    if(mapContacts.get(acc.id).contacts.size()>0)
    {
        acc.adderror('Account cannot be deleted');
    }
}                                       

}

Best Answer

Your trigger is a Before Insert/Update. Try:

trigger DoNotDeleteAccountHavingRelatedContact on Account (before delete)

And do replace Trigger.new with Trigger.old

** UPDATE **

Another commenter raised the issue that there was also a code problem. Please find an updated sample below

trigger DoNotDeleteAccountHavingRelatedContact on Account (before delete)  
{  
    List<Account> accList = new List<Account>();  
    Set<id> accIdSet = new Set<id>();  
    for(Account acc : Trigger.old)  
    {  
        accIdSet.add(acc.id);  
    }  

    Map<Id, Account> accts = new Map<Id, Account>([Select Id, (Select Id from contacts) from Account where id in :accIdSet]);

    for(Account acc : Trigger.old)
    {
        if(accts.get(acc.id).contacts.size()>0)
        {
            acc.adderror('Account cannot be deleted');
            }
        }                                       

}