I've only just started using apex so I'm having trouble pinpointing what is wrong with this code. It is a trigger on accounts which is intended to cycle through all contacts belonging to an account after the account's billing address is updated, and if their mailing address is the same as the account's old billing address, update the contact's to the new one on the account.
Can anyone shed some light on what is going wrong here?
trigger CascadeAddressUpdate on Account (after update)
{
/*If the billing address is changed, check all contacts of this account
who have their mailing address set to the billing address and update them*/
String oldBillingStreet = '';
String oldBillingCity = '';
String oldBillingState = '';
String oldBillingCountry = '';
String oldBillingPostalCode = '';
for (Account a : Trigger.new)
{
oldBillingStreet = Trigger.oldMap.get(a.Id).BillingStreet;
oldBillingCity = Trigger.oldMap.get(a.Id).BillingCity;
oldBillingState = Trigger.oldMap.get(a.Id).BillingState;
oldBillingCountry = Trigger.oldMap.get(a.Id).BillingCountry;
oldBillingPostalCode = Trigger.oldMap.get(a.Id).BillingPostalCode;
List<Contact> contacts = new List<Contact>([SELECT Id,
FirstName,
LastName,
MailingStreet,
MailingCity,
MailingCountry,
MailingState,
MailingPostalCode
FROM Contact WHERE AccountId = :a.Id]);
//Cycle through list of contacts
for (Contact c : contacts)
{
//If the contact's address information matches the old account address information, change contact address to new account address.
if (c.MailingStreet == oldBillingStreet)
{
c.MailingStreet = a.BillingStreet;
}
if (c.MailingCity == oldBillingCity)
{
c.MailingCity = a.BillingCity;
}
if (c.MailingState == oldBillingState)
{
c.MailingState = a.BillingState;
}
if (c.MailingCountry == oldBillingCountry)
{
c.MailingCountry = a.BillingCountry;
}
if (c.MailingPostalCode == oldBillingPostalCode)
{
c.MailingPostalCode = a.BillingPostalCode;
}
}
}
}