trigger AccountTrigger on Account (before delete) {
map<id,account>accmap=new map<id,account>( [select id, (select id from cases) from account where id in:trigger.oldmap.keyset() ]);
for (account a :trigger.old){
if(accmap.get(a.id).cases.size()>0){
a.adderror('you cannot delete the account as it has related
case records');
}
}
}
the above trigger will work absolutely fine, but the below code will fail , check this below code
trigger AccountTrigger on Account (before delete) {
for (account a : [select id, (select id from cases) from account where id in:trigger.oldmap.keyset() ]){
if(a.cases.size()>0){
a.adderror('you cannot delete the account as it has related
case records');
}
}
}
this above code will not give the required error before delete.
Any guess why ?
If you try to execute it will throw an error : System.FinalException: SObject row does not allow errors
as you can see the execution context is not the trigger context in the second piece of code its running over collection of account records although we are using trigger.oldmap to get the record ids, where as in the first code its running over the trigger.old records collection.
Hence we can say “You can you use the addError method for only those records that are available in Trigger Context. “
Good
Very Informative .Thanks for sharing