+ Start a Discussion
Raja JammulaRaja Jammula 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: oppTrigger: execution of AfterUpdate caused by: System.FinalException: Cannot modify a collection while it is being iterated.

Hi all can you please help me on this:
I am getting the above error 
List<req> reqlist = new List<req>();        
        set<Id> accountIds = new set<Id>();        
        
        for (opp op : opps) {
              accountIds.add(op.AccountId);
        }
        
        List<req> ExReq = new List<req>([Select Id, Type__c, Account__c, opp__c,stat__c,Opp__r.Is_Upd__c FROM req Where Account__c =:accountIds                                  
                                    AND Opportunity__c IN:opps AND Type__c = 'XYZ']);
        
        List<req> reqcan = new List<req>
        Integer reqIndex = 0;
        
        for(req req : ExReq){
            if(req.Opp__r.Is_Upd__c == true){
                req.stat__c = 'Cancelled';
                reqcan.add(req);
                ExReq.remove(reqIndex);
            }
            reqIndex = reqIndex + 1 ;
        }
        
        if(!reqcan.isEmpty()){
            update reqcan ;
        }
Best Answer chosen by Raja Jammula
Glyn Anderson 3Glyn Anderson 3
Raja,  Like the error says, you can't modify a collection while you are iterating it.  The solution is to iterate a copy of it instead.  Try using the clone() method, like this:

<pre>
        for(req req : ExReq.clone()){  // <== iterate a copy
            if(req.Opp__r.Is_Upd__c == true){
                req.stat__c = 'Cancelled';
                reqcan.add(req);
                ExReq.remove(reqIndex);
            }
            reqIndex = reqIndex + 1 ;
        }
</pre>

All Answers

Glyn Anderson 3Glyn Anderson 3
Raja,  Like the error says, you can't modify a collection while you are iterating it.  The solution is to iterate a copy of it instead.  Try using the clone() method, like this:

<pre>
        for(req req : ExReq.clone()){  // <== iterate a copy
            if(req.Opp__r.Is_Upd__c == true){
                req.stat__c = 'Cancelled';
                reqcan.add(req);
                ExReq.remove(reqIndex);
            }
            reqIndex = reqIndex + 1 ;
        }
</pre>
This was selected as the best answer
Glyn Anderson 3Glyn Anderson 3
Raja,  Did my suggestion solve your problem?  If so, please mark the question as solved.  If not, let me know and perhaps I can come up with a better idea.  Thanks!