Created
December 22, 2017 21:13
-
-
Save dsilvadeepal/54be5a05a2f3ffad6ecc53914cb79e35 to your computer and use it in GitHub Desktop.
When an account's phone number is updated, all related contact's 'Other Phone' must be updated. Do not update the contact's phone if the contact's country differs from the account's country
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
When an account's phone number is updated, all related contact's 'Other Phone' must be updated | |
Do not update the contact's phone if the contact's country differs from the account's country | |
*/ | |
trigger UpdateContactPhone on Account (before update) { | |
for(Account acc : Trigger.new){ | |
//Make sure the phone number is populated | |
if(acc.Phone != null){ | |
//Find relevant contacts | |
List<Contact> contacts = [SELECT Id, MailingCountry | |
FROM Contact | |
WHERE AccountId = :acc.Id]; | |
//Loop thru and update each contact | |
for(Contact con : contacts){ | |
if(con.MailingCountry != null && con.MailingCountry == acc.BillingCountry) { | |
con.OtherPhone = acc.Phone; | |
} | |
} | |
update contacts; | |
} | |
} | |
} | |
//Test Class | |
@isTest | |
private class UpdateContactPhoneTest { | |
@isTest static void updatePhoneOnAccount(){ | |
String country = 'US'; | |
Account acc = new Account(); | |
acc.Name = 'Windsor Hotels'; | |
acc.BillingCountry = country; | |
insert acc; | |
List<Contact> contacts = new List<Contact>(); | |
for(Integer i = 0; i < 5; i++){ | |
String iString = String.valueOf(i); | |
Contact myCon = new Contact(); | |
myCon.FirstName = 'Z'+iString; | |
myCon.LastName = 'Z'+iString; | |
myCon.AccountId = acc.Id; | |
myCon.MailingCountry = country; | |
contacts.add(myCon); | |
} | |
//Create a contact of a diff country | |
Contact diffCon = new Contact(); | |
diffCon.FirstName = 'Alisha'; | |
diffCon.LastName = 'Matts'; | |
diffCon.AccountId = acc.Id; | |
diffCon.MailingCountry = country+'A'; | |
contacts.add(diffCon); | |
insert contacts; | |
String phoneNumber = '4350987878'; | |
acc.Phone = phoneNumber; | |
update acc; | |
contacts = [SELECT OtherPhone | |
FROM Contact | |
WHERE AccountId = :acc.Id | |
ORDER BY FirstName ASC]; | |
//Assert in loops | |
// for(Contact con : contacts){ | |
// System.assertEquals(phoneNumber, con.OtherPhone); | |
//} | |
System.assertEquals(phoneNumber, contacts.get(1).OtherPhone); | |
System.assertEquals(null, contacts.get(0).OtherPhone); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment