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
Sam AlexSam Alex 

Iterate through the records of Standard Account Object

Hi,

I want to iterate though the records of Account object inside a trigger of another Object. I tried to do it as follows,

trigger CCTriggerToUpdateAccounts on CC__c (before insert, before update) {
    List<Account> accountList = [SELECT MyField__c FROM Account];
    CC__c[] configs = Trigger.new;
    
    for (Configuration__c c :configs){
        for(Account a: accountList){
            a.Sync_to_AG__c = c.CCID__c;
        }
        update accountList;
    }
}

It works. But The Account iteration goes for several times. I only have 1 Account in my list. 

How can I make it to iterate according to the number of records in the Account object?

Please Help me. Thank you very much in advance.
 
kiranmutturukiranmutturu
Please go through this https://help.salesforce.com/apex/HTViewSolution?id=000133752&language=en_US (https://help.salesforce.com/apex/HTViewSolution?id=000133752&language=en_US) also https://help.salesforce.com/HTViewSolution?id=000002357&language=en_US (https://help.salesforce.com/HTViewSolution?id=000002357&language=en_US)
Shashikant SharmaShashikant Sharma
Please explain your problem more.

What is this field CCID__c ? 
Why are you querying all the accounts ?
MithunPMithunP

Hi Sam,

Try to use "Map" collection and get account details from map, so that we can reduce unnecessary loops.

Take a look here: http://www.sfdc99.com/2014/01/25/use-maps-navigate-across-lists/

Best Regards,
Mithun.
Iqrar AhmedIqrar Ahmed
Hi sam,
 This is happening because your are iterating account inside a loop that iterating the inserted or updated records according to your code snippet your tigger is only for single record not for bulk so sperate both logic and  Do this work like following 
 
  trigger CCTriggerToUpdateAccounts on CC__c (before insert, before update) {
        List<Account> accountList = [SELECT MyField__c FROM Account];
        CC__c[] configs = Trigger.new;
        for(Account a: accountList){
            a.Sync_to_AG__c = configs.CCID__c;
          }
        update accountList;
  }
Sam AlexSam Alex
Thankyou all for your responses.

What I am trying to do is update a custom field in Account object when I am updating a custom object. When I add a value to CCID field in my custom object I want that value to be in a field in Account object.

If I add "1" to CCID in custom object, value "1" should be go to "Sync" field in ALL the Account records.

What would be the best way to do this?
Iqrar AhmedIqrar Ahmed
Dear sam,
This is same work i have post above your work will be fine by implementing above code of me.
Best Regards
IQRAR AHMED