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
Aditya RautAditya Raut 

Can anyone suggest me the optimized trigger for the followiing condition? -- Whenever we try to delete an account, if account has related contact to it, it should throw error.

Best Answer chosen by Aditya Raut
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Aditya,

Can you try the below trigger on Account.
 
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');
            }
        }                                       

}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,