1

Trying to get Account field "Phone" to populate "Main Office Phone" on Contact upon creation of a new contact. This is some copied code that I tried to use as a sample, but I have a Variable Does Not Exist error on listConForPhoneUpdate. Can anyone see my possible error(s)?

trigger ContactPhone on Account (before update) 
{
    for (Account acc : Trigger.New)
    {
        List<Contact> listConForPhoneUpdate = [Select Phone from Contact 
            where Phone != null and AccountID =: acc.id];

        for(Contact con : listConForPhoneUpdate)
            con.Phone = acc.Phone;
    }

    update listConForPhoneUpdate;
}
  • calling the update in a before trigger, even on a related object, is problematic and will bite you later if not now. – Lurker Apr 10 '18 at 17:11
1

In Apex {} defines a scope and listConForPhoneUpdate is declared inside a scope but referenced outside it hence the compile error. Correct code indenting would make that clearer.

Your current trigger is trying to propagate changes on Account to existing child Contact objects. You would need a Contact trigger to set the Phone when a new Contact is created.

  • In other words, listConForPhoneUpdate was declared in a for loop.. Can't do that if you want to use it outside of it – EricSSH Jun 26 '14 at 21:09
  • @EricSSH To be pedantic in a block scope that just happens to be the body of the for loop... – Keith C Jun 26 '14 at 21:12
1

Try the code below. You've defined "listConForPhoneUpdate" inside the for loop. I don't think it is accessible outside the for loop.

trigger ContactPhone on Account (before update) 
{
List<Contact> listConForPhoneUpdate;

    for (Account acc : Trigger.New)
        {
        listConForPhoneUpdate = [Select Phone from Contact where Phone != null and AccountID =: acc.id];
        for(Contact con : listConForPhoneUpdate )
            con.Phone = acc.Phone;
        }
update listConForPhoneUpdate;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.