2
trigger delAccountWithoutOpportunity on Account (before delete) {
    for(Account a : [select ID, (select ID from Opportunities) from Account where ID in: trigger.Old]){
       System.debug(a.Opportunities.size()); //resulting in right number of opportunities associated
       if(a.Opportunities.size() > 0) 
           a.addError('cannot delete');
    }
}

On deletion of account with 0 opportunities, it gets deleted. On deletion of account with greater than 0 opportunities associated, it gives

There's a problem saving this record. You might not have permission to edit it, or it might have been deleted or archived. Contact your administrator for help.

I am new to salesforce, trying my best to learn as fast as I can. Please Help me figure out where I am getting the concept of triggers wrong. Thankyou.

2

You need to add the error to a record in Trigger.old or Trigger.oldMap in order to prevent deletion. You can write your code like this:

trigger delAccountWithoutOpportunity on Account (before delete) {
  Map<Id, Account> accounts = new Map<Id, Account>([
    SELECT Id FROM Account WHERE AND Id IN
      (SELECT AccountId FROM Opportunity WHERE AccountId = :Trigger.old)
  ]);
  for(Id recordId: accounts.keySet()) {
    Trigger.oldMap.get(record.Id).addError('Cannot delete');
  }
}
| improve this answer | |
  • Worked. Thankyou :) – anita hemrajani Jun 27 '19 at 6:58
  • Sir, Why didn't it work when i was adding error to account? – anita hemrajani Jun 27 '19 at 6:58
  • 1
    @anitahemrajani the issue was that you were adding error to Accounts retrieved via SOQL and not the ones which were being processed by the trigger. Technically same records, but the mechanism that picks up trigger errors was not able to pick up yours. – Bartosz Śliwiński Jun 27 '19 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.