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;
}
1
  • calling the update in a before trigger, even on a related object, is problematic and will bite you later if not now.
    – Lurker
    Commented Apr 10, 2018 at 17:11

2 Answers 2

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.

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

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;
}
0

You must log in to answer this question.

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