+ Start a Discussion
SandrineSandrine 

Error while duplicating oOpportunityContactRole: Cannot modify a collection while it is being iterated.

Hello,

I have below error whicle i use the code
Cannot modify a collection while it is being iterated.
 
List<OpportunityContactRole> opportunityContactRoleList = (List<OpportunityContactRole>)Database.query(VCloneRecord.getCreatableFieldsSOQL('OpportunityContactRole','OpportunityId ='+'\'' + currentOpp.Id + '\'',NULL));
        List<OpportunityContactRole> cloneOpportunityContactRoleList = new List<OpportunityContactRole>();
        for (OpportunityContactRole item : opportunityContactRoleList) {
            OpportunityContactRole q = item.clone(false, true);
            q.OpportunityId = oppClone.id;
            If(q.OpportunityId != NULL)
                opportunityContactRoleList.add(q);
        }
        insert opportunityContactRoleList;

any suggestions, please ?
AbhishekAbhishek (Salesforce Developers) 
Hi Sandrine,

The below developer blogs also have faced the same issue, Can you try the suggestions mentioned below,

https://developer.salesforce.com/forums/?id=906F00000008yugIAA

https://success.salesforce.com/answers?id=90630000000CxvKAAS

https://salesforce.stackexchange.com/questions/93426/cannot-modify-a-collection-while-it-is-being-iterated/93430

I hope you find the above information is helpful. If it does, please mark as Best Answer to help others too.

Thanks.
David Zhu 🔥David Zhu 🔥
It is because you change list opportunityContactRoleList when.looping through the list.
you may change your code a bit.
List<OpportunityContactRole> opportunityContactRoleList = (List<OpportunityContactRole>)Database.query(VCloneRecord.getCreatableFieldsSOQL('OpportunityContactRole','OpportunityId ='+'\'' + currentOpp.Id + '\'',NULL));
        List<OpportunityContactRole> cloneOpportunityContactRoleList = new List<OpportunityContactRole>();
        for (OpportunityContactRole item : opportunityContactRoleList) {
            OpportunityContactRole q = item.clone(false, true);
            q.OpportunityId = oppClone.id;
            If(q.OpportunityId != NULL)
               cloneOpportunityContactRoleList.add(q);
        }
        insert cloneOpportunityContactRoleList;