Trigger – Prevent Account from Deletion if it has related Opportunities

Prevent Account from Deletion if it has related Opportunities
Prevent Account from Deletion if it has related Opportunities

Hello dear coders, here is another apex trigger scenario – If the account has related opportunities then we should not able to delete that account. Here is the code for it. Do watch the video for detail understanding.

				
					trigger AccountTrigger2 on Account (before delete) {

    if(Trigger.isBefore && Trigger.isDelete) { 
        
        List<Opportunity> oppr = [SELECT ID, AccountId From Opportunity Where AccountId =: Trigger.old];
        
        if(!oppr.isEmpty() && oppr.size() > 0 ) { 
            for(Account acc: Trigger.old ) { 
                acc.addError('You cannot delete this Account it has  Opportunity related to it.');
            }
        }
    }
    
}
				
			

In this video we have discussed the trigger in detail.

This Post Has 2 Comments

  1. sv

    why video is private

    1. admin

      We will make them public soon.

Leave a Reply