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
ranadheer reddy chaduvuranadheer reddy chaduvu 

I have a trigger that prevents deletion of parent record if child exists ...here my parent object name is Apple__c......,my child object api name is Orange__c

I have a trigger that prevents deletion of parent record if child exists ...here my parent object name is Apple__c......,my child object api name is Orange__c....sohere i wrote a trigger on parent object

trigger preventingdeletion on Apple__c (before delete) {

  for(Apple__C a:[select id,name,(select id from Orange__r ) from Apple__C where id in:Trigger.oldmap.keyset()]){
   if(a.Orange__r!=null&&a.Orange__r.size()>0){
   a.adderror('dont delete');
   }
   }

}



The above one is my trigger .....here the problem is trigger saved but its not showing the desired validation error message 

its showing the below error while deleteing the parent record its showing below error ....but my error message in trigger is "dont delete"


There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger preventingdeletion caused an unexpected exception, contact your administrator: preventingdeletion: execution of BeforeDelete caused by: System.FinalException: SObject row does not allow errors: Trigger.preventingdeletion: line 5, column 1".


how to solve this thanks.





ShashForceShashForce
Hi,

You can use the addError method for only those records that are avaliable in Trigger Context. Please try something like this and you should be good:

for(Apple__C a:[select id,name,(select id from Orange__r ) from Apple__C where id in:Trigger.oldmap.keyset()]){
   if(a.Orange__r!=null&&a.Orange__r.size()>0){
    Apple__c actualRecord = Trigger.oldMap.get(a.Id);
   actualRecord.adderror('dont delete');
   }
   }

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
Anoop yadavAnoop yadav
Hi Ranadheer,

Try the below code.

trigger preventingdeletion on Apple__c (before delete) {
    
    for(Orange__c orange :[Select Id, Name, Apple__c FROM Orange__c WHERE Apple__c IN :Trigger.oldMap.keySet()]){
        Trigger.oldMap.get(orange.Apple__c).addError('Can not Delete!!');
    }
}
This will help you show the desired error message.