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
sachin joshi 14sachin joshi 14 

Trigger (before delete)

trigger AccountDeletion on Account (before delete) {
        for (Account a : [SELECT Id FROM Account
                     WHERE Id IN (SELECT AccountId FROM Opportunity) AND
                     Id IN :Trigger.old]) {
            'Cannot delete account with related opportunities.');
What is meaning of Trigger.oldMap.get(a.Id).addError() and why can't we use a.addError( ) as it is iterating only over the records which has opportunity.
Please Explain it will be a great help. 
Amit Chaudhary 8Amit Chaudhary 8
You need to set the Error on Trigger record only. There may be possiblity by your query any other record will come. 

addError(errorMsg)Marks a record with a custom error message and prevents any DML operation from occurring.Signature

public Void addError(String errorMsg)

The error message to mark the record with.

When used on in before insert and before update triggers, and on Trigger.old in before delete triggers, the error message is displayed in the application interface. 

If you doing SOQL means that record is not part of you DML operation. That record will come directly from Database.

Please let us know if this will help u
sachin joshi 14sachin joshi 14
Thanks for your response Amit bt I am still confuse I want to know that a is iterating over those records which has opportunity so why i can not use a.addError( ) in place of Trigger.oldMap.get(a.Id).addError()?
Amit Chaudhary 8Amit Chaudhary 8
In your code your are getting list of account by SOQL. If you will use Trigger.New then you can use a.addError