Sunday 10 September 2017

How To Stop Deletion Of Parent Record If Child Record Exist In Salesforce Using Triggers.

Arpit Sharma
In this tutorial we will see how we can stop deletion of parent record basis on condition. As we have already learn Simple Example i.e Stop deletion of parent record using configuration.

Now let's come on this, Suppose we have a scenario in which we need to stop deletion of parent record when child record exist basis on condition either on parent or child, we can handle this scenario by using trigger.

Now Let's take on example 

Suppose we have Account Object and Contact object and if we want to stop deletion of parent account record if any child contact record name starts with "Test".

We can handle this scenario using trigger having before delete event

Below is sample code snippet of above scenario.

trigger AccountTrigger on Account (before delete) {
    //reterieve all contacts releated account that is currently deleting
    Map<Id,Account> accountWithContacts = new Map<Id,Account>([SELECT 
            ID,(SELECT ID,Name FROM Contacts) 
            FROM Account 
            WHERE ID IN:Trigger.old]);
    //iterate over trigger.old context variable record        
    for(Account accRecord : Trigger.old){
       //reterive contact records associate with account
       for(Contact accContact :accountWithContacts.get(accRecord.ID).contacts){
           //if contact start with Test then stop deletion of account record
               accRecord.addError('You cannot delete this account because contact associate with this account have name test.');

Guys share this tutorial if you like it.

About the Author

Arpit Sharma / Author & Editor

Certified Salesforce Developer | Salesforce Developer at Cognizant | Blogger


Post a Comment