0

I am new to Saleforce coding but I have some prior development experience in some other Programming language as well. I am trying to learn triggers by myself now.

Can some one help me to understand the below code especially how the List (contactList) and temporary contact variable (myCon) are related.

trigger UpdateContactAddr on Account (before update) {
    for(Account acc: Trigger.new){
        List<Contact> ContactList = [Select Id from Contact where Contact.Id = :acc.Id];
        for(Contact myCon: contactList){
            myCon.MailingCountry = acc.BillingCountry;
        }
        update ContactList;
    }
}
  • Because my doubt is that we are getting full list of all Contacts from an Account in list variable.
  • Inside loop - Then for each record in <contactList> its assigned to myCon temporary variable one by one and move Account variable acc in it
  • Then finally outside the loop updating the List - ContactList directly

Can you please help me to understand, how ContactList is updated directly as the actual value is just moved to myCon only and no assignment happened to ContactList and the piece of code works

1
  • 1
    In your query's where clause Contact.Id = :acc.Id, Contact Id would not be equal to Account Id, unless it is a Person Account (which is a different story), so it should be AccountId = :acc.Id
    – Raul
    Feb 12, 2017 at 23:06

1 Answer 1

2

Iterating over a list like this:

for(Contact myCon: contactList){
    // myCon represents each record in a list
}

is same as:

for(Integer count = 0; count < contactList.size(). count++){
    // contactList[count] - now this represent each record
}

Its a short hand of iterating over a list.

Now will try to explain the code:

trigger UpdateContactAddr on Account (before update) {

    // iterate over all the updated records
    for(Account acc: Trigger.new){

        // query all Contacts where Account Id matches current Account record from list
        List<Contact> ContactList = [Select Id from Contact where AccountId = :acc.Id];

        // iterate over all contacts of current parent
        for(Contact myCon: contactList){

            // myCon represents contact record from list
            // you are modifying Mailing country on Contact with Account's Billing country
            // this would update be in your Contact list 
            myCon.MailingCountry = acc.BillingCountry;
        }

        // now at this point you are performing update operation
        // this would save all changes to Mailing country to Contacts
        update ContactList;
    }
}

You have SOQL and DML inside a for loop, which is a bad practice. Suggest you to learn from awesome Trailhead site. Refer this module for triggers.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .