You are getting this error because of this below lines
for (Opportunity opp : trigger.old){
opp.addError ('Opportunities can not be deleted');
}
Triggers can be used to prevent DML operations from occurring by calling the addError() method on a record or field. When used on Trigger.new records in insert and update triggers, and on Trigger.old records in delete triggers, the custom error message is displayed in the application interface and logged. More help i.e. Trigger Exceptions on this link.
You cannot use Trigger.Old
to addError
in After Update context.
You will have to surround that code of yours by checking the condition so that it runs only in before delete context. You will have to remove the above code from Trigger.IsUpdate
and Trigger.isAfter
condition and add a separate condition.
if(Trigger.IsDelete && Trigger.IsBefore){
for (Opportunity opp : trigger.old){
opp.addError ('Opportunities can not be deleted');
}
}
It is always a best practice to check in which context your particular code should execute.