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
Sindhu AmbarkarSindhu Ambarkar 

Getting error System.FinalException: Cannot modify a collection while it is being iterated.

Iam getting error while updating record.
<apex:page showHeader="false" controller="ap_SOQl">
     <apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection title="Account Page">
            
        <apex:outputText value="Enter Name :"> </apex:outputText>
            <apex:inputText value="{!aname}" />
            
          <apex:outputText value="Enter Phone No :"></apex:outputText>
        <apex:inputText value="{!aphone}"/>
            
            <apex:outputText value="Enter City"></apex:outputText>
            <apex:inputText value="{!acity}" />  
            
        </apex:pageBlockSection>
        
        <apex:pageBlockSection title="Actions">
            
        <apex:commandButton value="Insert.." action="{!mi}"/>
            <apex:commandButton value="Delete .." action="{!md}"/>           
           <apex:commandButton value="Update..." action="{!mu}"/>
            <apex:commandButton value="Retrieve .." action="{!ms}"/>
           <apex:commandButton value="Upsert..." action="{!mups}"/>
        </apex:pageBlockSection>
      <apex:pageBlockSection title="aaccount Records">
        <apex:pageBlockTable value="{!arecs}" var="items" title="Records" >
            
            <apex:column value="{!items.name}"/>
            
                <apex:column value="{!items.phone}"/>
            
            <apex:column value="{!items.billingcity}"/>   
            
        </apex:pageBlockTable>
          </apex:pageBlockSection>
        <apex:pageMessages ></apex:pageMessages>
        
        </apex:pageBlock>
         
    </apex:form>
</apex:page>
Controller
public class ap_SOQl{
    
    public string aname{set;get;}
    public string aphone{set;get;}
    public string acity{set;get;}
    public list<account>arecs{set;get;}
    
    public void mi()
    {
        integer i=[select count() from account where name=:aname];
        if(i==0)
        {
        account ac=new account();
        ac.Name=aname;
        ac.Phone=aphone;
        ac.BillingCity=acity;
        
        insert ac;
        apexpages.Message msg=new apexpages.Message(apexpages.Severity.CONFIRM , i+'Record(s) inserted Sucessfully');
        apexpages.addMessage(msg);
        }
        else
        {
             apexpages.Message msg2=new apexpages.Message(apexpages.Severity.ERROR,i+'Record(s) Already Exist');
            apexpages.addMessage(msg2);
            
        }
        arecs=[select name,phone,billingcity from account where name=:aname];
    }
    public void md()
    {
        list<account>ls=[select name,phone,billingcity from account where name=:aname];
        delete ls;
        apexpages.Message msg=new apexpages.Message(apexpages.Severity.WARNING , ls.size() + 'RecordC(s) Deleted Succesfully');
        apexpages.addMessage(msg);
        arecs=[select name,phone,billingcity from account where name=:aname];
     }
    
    public void mu()
    {
        list<account>ls=new list<account>();
        ls=[select name from account where name=:aname];
        for(account ac:ls)
        {
           ac.Name=aname;
            ac.Phone=aphone;
            ac.BillingCity=acity;
            ls.add(ac);
        }
        update ls;
        apexpages.Message msg=new apexpages.Message(apexpages.Severity.INFO , ls.size() + 'Record(s) Updates Succesfully');
        apexpages.addMessage(msg);
        arecs=[select name,phone,billingcity from account where name=:aname];
    }
    public void ms()
    {
        arecs=[select name,phone,billingcity from account where name=:aname];
    }
    public void mups()
    {
        list<account> ls = new list<account>();
        ls =    [select id,name from account where name = :aname];   
        integer n = ls.size();
        if( n== 0){
            account a = new account();
                    a.name = aname;
                    a.Phone = aphone;
                    a.BillingCity = acity;
                    upsert a;       // insert Record
                    n = 1;
                }
            else{
            
            for(account ac : ls){
                ac.name = aname;
                ac.Phone = aphone;
                ac.BillingCity=acity;
                upsert ac;      // Updates Record
            }
        }
            apexpages.Message mes1 = new  apexpages.Message(apexpages.Severity.CONFIRM, n + ' Record UPSERTED (Insert/Update) Successfully');          
            apexpages.addMessage(mes1);           
            arecs = [select id,name,phone,billingcity from account where name =: aname];        
    }
 
    
}

Can someone explain me 
pconpcon
The problem is that you are modifying a list of records that you are iterating over.  Lets take the following snippet from your code as an example
 
List<account> ls = [
     select name
     from account
     where name = :aname
];

for (account ac : ls) {
     ac.Name = aname;
     ac.Phone = aphone;
     ac.BillingCity = acity;
     ls.add(ac);
}
As we can see on line 11, you are trying to add the instance variable of "ac" back to the list "ls" that you are currently iterating over.  You cannot modify the list that you are currently iterating over.  Additionally, there is no need to do this because any changes to the object while iterating over the list in Apex will result in the object in the list being updated.  They are passed by reference not by value.  So, all you need to do is have the following:
 
List<account> ls = [
     select name
     from account
     where name = :aname
];

for (account ac : ls) {
     ac.Name = aname;
     ac.Phone = aphone;
     ac.BillingCity = acity;
}

 I would also like to take a moment and point out that you really should not have your last upsert inside of a loop.  This will cause you to quickly run out of DML calls for larger datasets.
Sindhu AmbarkarSindhu Ambarkar
thanks a lot
 
Aradhika Chawla 3Aradhika Chawla 3
That was really helpful, as you don't even realise that you are only updating not adding so no need of adding a element to list.