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
kcharubinkcharubin 

System.LimitException: Too many DML statements: 151

trigger closeTuoCasesWhenDefectFixed on Tuo_Defect__c (after update) {
    for(Tuo_Defect__c d : Trigger.new){
        if(d.Status__c == 'Closed - Fixed'){
            List<Tuo_Case__c> cases = [select Status__c, Solution__c from Tuo_Case__c where Tuo_Defect__c =: d.id];
            for(Tuo_Case__c c : cases ){
                c.Status__c = 'Solution Available';
                c.Solution__c = d.Resolution__c;
                update c;
            }
        }
    }
}

 I wrote the code above and it works fine when there are only a few Cases related to the Defect

Today I tried updating a Defect that has 77 related Cases and I get the following error message.

 

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger closeTuoCasesWhenDefectFixed caused an unexpected exception, contact your administrator: closeTuoCasesWhenDefectFixed: System.LimitException: Too many DML statements: 151".

 

I can't figure out how to get rid of this error message.

Any help would be greatly appriciated.

Best Answer chosen by Admin (Salesforce Developers) 
@anilbathula@@anilbathula@
Hi

This error is because you writing query and update operation inside a for loop.change your trigger to this:-

trigger closeTuoCasesWhenDefectFixed on Tuo_Defect__c (after update) {
Map<id,Tuo_Defect__c> varmap=new Map<id,Tuo_Defect__c>();
list<Tuo_Case__c>tcs=new list<Tuo_Case__c>();

for(Tuo_Defect__c d : Trigger.new){
if(d.Status__c == 'Closed - Fixed'){
varmap.put(d.id,d);
}
}
if(!varmap.isempty()){
List<Tuo_Case__c> cases = [select Status__c, Solution__c,Tuo_Defect__c from Tuo_Case__c where Tuo_Defect__c =: varmap.keyset()];
for(Tuo_Case__c c : cases ){
c.Status__c= 'Solution Available';
c.Solution__c = varmap.get(c.Tuo_Defect__c).Resolution__c;
tcs.add(c);
}
update tcs;
}
}