0

I can't understand why we are referring to the Trigger.old and Trigger.oldMap in this before delete trigger since both of those are used to return the old versions of sObject records. And we are not changing anything here so why do we need to use the old versions?

trigger accountDeletion on Account (before delete) {

// Prevent the deletion of accounts if they have related opportunities.
for (Account a : [SELECT Id FROM Account
                 WHERE Id IN (SELECT AccountId FROM Opportunity) AND
                 Id IN :Trigger.old]) {
    Trigger.oldMap.get(a.Id).addError(
        'Cannot delete account with related opportunities.');
}

}

If I remove all Trigger.old and Trigger.oldMap references in the code above, I get errors/exceptions:

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

trigger accountDeletion on Account (before delete) {

// Prevent the deletion of accounts if they have related opportunities.
for (Account a : [SELECT Id FROM Account
                 WHERE Id IN (SELECT AccountId FROM Opportunity)]) {
    a.addError(
        'Cannot delete account with related opportunities.');
}

}

Can anyone please explain to me the logic behind using Trigger.old and Trigger.oldMap? Thanks!

1
  • Separate from your question, this query will run longer and longer as you add Opportunities to your database, as a result of the unfiltered subquery select AccountId from Opportunity. Commented Mar 25, 2015 at 19:20

2 Answers 2

1

CyberJus explained first one pretty well. It gives exception on your other trigger because you are fetching all accounts with opportunity and adding error to it. You can only add error to that account for which the trigger was fired.

Account a : [SELECT Id FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity)]

Moreover i have a suggestion you should check if their is an open opportunity rather than checking if their is an opportunity again that's your business call.

2

In a delete trigger, you have to reference the old values. There are no new values, since the result of new would be deletion.

That trigger checks if there are Opportunities existing for the Accounts records you plan to delete and adds an error to the to prevent their deletion.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .