+ Start a Discussion

Updating ACCOUNT field within an OPPORTUNITY loop

Can somone tell me what I'm missing here?   :-/   Just trying to write data back to the Account.  Surrounding THIS for loop is an Opportunity for-loop, if that matters.  :-/  



                        for ( Account AccountRec : [Select Id, Name, Last_PhoneCall_Attempt__c from Account where Id = :OpportunityRec.AccountId] )
                            OpportunityRec.Name = AccountRec.Id;  // returns the RIGHT ID...
                            AccountRec.Name = 'TonyBaloney';      // does NOT reset Name on Account to this value..!
                            AccountRec.Last_PhoneCall_Attempt__c = Date.Today();    // same issue...
                        OpportunityRec.Last_PhoneCall_Attempt__c = Date.Today();


Amalena --


Missing some context here --  are you doing this code inside a trigger on Opportunity? 


  • Why are ou setting OpportuniyRec.name to the AccountRec's id?  Oppo names are strings and wouldn't normally be the id of their associated Account
  • To update an Account , you need a DML Update statement : update AccountRec;


If you are doing this inside a for loop on Opportunity, then you may run into governor limits....especially in any batch situations.  You should build a list of updated Accounts and update the accountList in one statement

Rahul S.ax961Rahul S.ax961

Hi AMalena,



In the 1st line(for loop),  OpportunityRec.AccountId will return single ID. I believe you are iterating loop for a single record, which is not needed.

This can be done simpler way.




Account AccountRec = new Account([Select Id, Name, Last_PhoneCall_Attempt__c from Account where Id = :OpportunityRec.AccountId]);
// I Believe OpportunityRec is initialized previously
AccountRec.Name = 'TonyBaloney';
AccountRec.Last_PhoneCall_Attempt__c = Date.Today();
update AccountRec;
OpportunityRec.Name = AccountRec.Id;
OpportunityRec.Last_PhoneCall_Attempt__c = Date.Today();
update OpportunityRec;


Let me know if my understanding on your code was correct?




Thanks for the help.  I'll try this out.   (to answer a previous post, it was in a Trigger, and altering the Name was just a TEST to verify I was actually retrieving the Account ID).


I was able to extrapolate exactly what I needed from the help given above.  Thanks, all!!   Learning curve is smoothing out.  Yay.   :robottongue:  


Remember to mark posts with solutions so others with the same problem as you can quickly find the answers they are seeking. Help build the Salesforce knowledge base.