[SalesForce] Can anyone please explain the logic in this ‘before delete’ trigger

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!

Best Answer

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.

Related Topic