Preface – This post is part of the Core Apex Tools series.
Every trigger in Salesforce will have a loop! These are very important to learn!
Loops are a popular coding tool that let you repeatedly execute code.
A FOREACH loop is the most popular type of loop in Apex. FOREACH loops let you repeatedly execute code on every element of a list:
List<Contact> allContacts = [SELECT Id FROM Contact];for (Contact currentContact : allContacts) {// This is my contact ID. People love me! currentContact.Best_Friend__c = '003i000000Mnm1R';}
Remember, the green highlighted code is the most important – here it represents the loop. Everything inside is the code that executes for each Contact in our list. There are two important variables in this loop: currentContact and allContacts.
currentContact is the variable we designate to represent the current Contact in each iteration of the loop. If we’re iterating over 200 contacts, currentContact will separately represent each contact, one-by-one, until all 200 have gone through the loop. We preface this variable with Contact to let Salesforce know what kind of object it is.
allContacts is the List the loop will iterate over. Each Contact in this list will run through the code inside the brackets { } exactly once!
A traditional FOR loop lets you repeatedly execute code a specific number of times:
for (Integer i = 0; i < 5; i++) {// Create five new imaginary friends! Contact friend = new Contact(); friend.FirstName = 'Kate';friend.LastName = 'Upton #' + i;friend.Best_Friend__c = '003i000000Mnm1R'; insert friend;}
The traditional FOR loop is a little different because instead of iterating over a list, you’re iterating over a defined number of iterations.
In the very first line this reads:
1. For a new integer we define as “i” that starts at zero
2. Iterate while “i” is less than 5
3. After each iteration, increment “i” by one
Notice how we use the integer “i” inside the loop! Five Kate Uptons will be created with the exact names: “Kate Upton #0”, “Kate Upton #1”, “Kate Upton #2″…
Now what am I going to do with five Kate Uptons all to myself?
Salesforce coding party!!
Next post: Comparison operators!
Hi David,
Thanks you so much for your kind tutorials. It really helped me to write my first code with complete clarity on what I am doing.
Here I wrote a code for creation of 5 tasks when a case is created.
1. can you let me know if this the efficient way of writing code or can it be more efficient than what it is??
trigger FiveTasksOnCase on Case (after insert) {
// create a list to insert 5 tasks
list allTasks = new list ();
//base line code to work on target object
for(case newCase: Trigger.new){
// insert a loop to iterate over task creation
for(integer i=1; i<=5; i++){
task tt = new task();
tt.subject = 'Task' + i + newCase.subject;
tt.WhatId = newCase.id;
tt.OwnerId = newCase.OwnerId;
tt.Status = 'In Progress';
tt.Priority = 'Normal';
// add each task to our list
allTasks.add(tt);
}
}
// insert our task records in database
insert alltasks;
}
David,
Isn’t it also true that the Id field will be queried whether you explicitly call on it or not? E.g,
SELECT Email, Id
is equivalent to
SELECT Email
Awesome site!!
True!
public class testpage {
Lead L = new Lead();
List LeadManagers=[select Lead_Manager__c from Major_Market_Lead_Manager__c];
for (Major_Market_Lead_Manager__c Lm: LeadManagers) {
List results = [Select Lead_Manager__c, Count(Id) total From Lead where Lead_Manager__c IN (:Lm.Lead_Manager__c )Group By Lead_Manager__c];
}
public List getLeadManagers(){
return LeadManagers;
}
}
Error occur that says For Loop not correct :(
LeadManagers List & the results list within the for loop have formatting issues, should be in this kind of format:
List LeadManagers = [select Lead_Manager__c from Major_Market_Lead_Manager__c];
List variableName = [SELECT … FROM API_Object_Name];
Hi David,
A very basic question:-
List peopleToSpam = [SELECT Id, Email FROM Contact];
List peopleToSpam1 = [SELECT Id FROM Contact];
Are both of the above Lists contain same values.
What i mean to say is that peopletospam contains Email and Id only of all the contacts or every field of Contact.?
same question for peopletospam1 contact?
Different values in each!
You can only access the fields that are queried, so you’ll have more fields available in peopleToSpam. Salesforce requires you to explicitly state which fields to query to reduce the amount it needs to cache, making the platform faster.
Thanks for the reply David.
However how come you use currentContact.Best_Friend__c in your first example when you are just querying id into the allContacts List.
your eg below:-
List allContacts = [SELECT Id FROM Contact];
for (Contact currentContact : allContacts) {
// This is my contact ID. People love me!
currentContact.Best_Friend__c = ‘003i000000Mnm1R’;
}
Great question!
If we’re just setting the value of a field, we don’t need to know it’s current value.
If we were to check the value of a field, ie, (currentContact.Best_Friend__c != null), we’d need to query the value!
Duh!!! for a second I thought I caught a google engineer on the wrong foot…
hehe..
anyways thanks for the explanation man.. cheers..
Hi, I echo all other comments that this site is great. I admit to having a tough time getting through Head First Java but I’ll try it again after reading this.
In the first example above, can you just explain what has happened by replacing the ‘normal’ : trigger.new with : allContacts ?
If I’m understanding it correctly, you aren’t triggering on new contacts, so what would you be triggering on? Would this be a case where the trigger would run against the Account and update all associated Contacts based on a SOQL query? I’m struggling with what triggers this update on each contact’s best friend.
Thanks
Poor example by me! There is no actual trigger in this example (because every trigger would have a Trigger.new somewhere)!
I was just trying to show that you can loop through Trigger.new OR any other list!
I mean are you trying to change the Id value of all the contacts?
There’s a lookup field on Contacts called Best Friend and this lookup field points to another Contact!
All we’re doing in the code is populating the Best Friend lookup field to one Contact in particular – the one with the ID 003i000000Mnm1R
Thank you David..Got it finally
do we always need to populate lookup fields with ids
Yes!
David,
I am really confused with the foreach loop..
step 1.. List allContacts = [SELECT Id FROM Contact];
step 2. .for (Contact currentContact : allContacts) {
// This is my contact ID. People love me!
step 3… currentContact.Best_Friend__c = ‘003i000000Mnm1R’;
step 1 :Query is written to retrieve Id from contacts..
step 2. for all current contacts( i mean all contacts ) you are trying to retrieve the id from all the contacts? :-(
step 3. assigning the id value to the current contact.Best_Friend__c the number of times loop iterates..
David,
This post – you are ridiculous (and I mean that in the best way)! I can’t thank you enough for putting this site together. I’m coming from a background somewhat similar to yours – had the briefest exposure to coding in high school, but went down a completely different path in college – and have wanted to really learn how to code for ages now. Attending the webinar you put on yesterday, and working through your site, has finally pushed me over the edge and gotten me to commit to learning Apex and VF. Those JavaScript, Ruby, and Pearl books sitting on my shelf might actually see some use now!
Hey, maybe you could work with salesforce.com to give the Apex workbook a face lift – it could use more contextual examples.
By the way, working at Google has been my dream for years – hearing about your path and experience has got me thinking about re-applying. I look forward to meeting you in person one of these days!
Thanks again David!
Great post Dave! I hope to see you at Dreamforce!
Thank you for getting me straight on this – I really appreciate it. –Tom
Hi David,
I am really enjoying your stuff, especially triggers and apex concepts. can you please write post on MAPS asap, eagerly waiting for “maps” .
Many thanks….. Madhu
I have almost an entire chapter dedicated to Maps, check it out!
https://www.sfdc99.com/2014/01/12/introduction-maps/
Hi David,
Great stuff — thank you for sharing with the Universe! :) Question about the allContacts list, will the code fail if you reference a field to update (i.e.: Best_Friend__c) if it is not in the SELECT query? I thought there was some situation that you had to include the field in the SELECT statement if you wanted to reference it down stream but I could be wrong. I appreciate your support –Tom B.
List allContacts = [SELECT Id FROM Contact];
for (Contact currentContact : allContacts) {
// This is my contact ID. People love me!
currentContact.Best_Friend__c = ‘003i000000Mnm1R’;
}
Hey Tom,
My pleasure!
You only need to do a SOQL query for the specific fields if all these are true:
– You need to know the current value of the field (not simply updating the value as I do in this post)
– The record is not part of the trigger. All fields of records entering the trigger are automatically queried!
Hope this helps!
David
hi david your tutorials are very good for begginers .i am new to salesforce .i am feeling some difficulty in understanding coding part
Thanks a lot David for making such a help full website.
Please add chapter 5 and 6.
I really appreciate the help you are providing to the Apex begineers
No problem!
Chapter 5 is a personal favorite of mine since it’ll really accelerate people into the world of intermediate/advanced Apex. Lots of jobs for people to find here!
Expect at least a couple posts this week!
David