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!
select AccountId from Opportunity
.