Creating For Loops in apex is needed for many different tasks you’ll be given as a Salesforce Developer.
Here are some ways you can implement For Loops in your code:
1 2 3 4 |
//loop for (variable : list_or_set) { code_block } |
For lists or set iteration:
Use this any time you want to loop over a set of records pulled from your Salesforce database.
1 2 3 4 |
//loop for (variable : [soql_query]) { code_block } |
Or Use this any time you are handling data from a method that returns a list or set.
1 2 3 4 |
//loop for (variable_list : [soql_query]) { code_block } |
Here is a real world example to help out.
Lets say you need to update all records for a custom object so they contain a new value for a custom field.
This could be needed if you want to add data to lookup fields retroactively!
In Apex Execute Anonymous you could write this and execute:
1 2 3 4 5 6 7 8 9 10 11 12 |
//Setup your List of records using the api name of the object. List<myobj__c> myobjs = [select id, name, customfield__c From myobj__c]; //Loop through the list of returned records For(myobj__c c : myobjs){ c.customfield__c = '003j0000000Xi18'; system.debug('Name of record '+ c.name); } //update your changed list now that you have changed the data. //if you dont use update the values are just stored in the memory of your session. Not in Salesforce. update myobjs; |