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');
}
}
}