This is a simple and easy code to understand for new salesforce developer.
trigger UpdateAccountPhoneNumberTrigger on Contact (before update) {
Set<id> IdCollect = new Set<id>(); For(Contact con :Trigger.New){ If (con.Phone != null){ IdCollect.add(con.AccountId); } } List<Account> acList = new List<Account>(); acList =[Select Id,Phone from Account Where Id IN:IdCollect];
//using simple map to put contact phone number Map <Id, string> conmap = new Map <Id, string>(); for(Contact c : trigger.New){ conmap.put(c.AccountId , c.Phone); } if(acList!=null){ for(Account ac : acList ){ ac.Phone = conmap.get(ac.Id); } } if(acList.size()>0){ Update acList; } }
Please mark it as best Answer if you find it helpful.
optimized, efficient, less number of lines and error less.
- Took care of null values
- Only works when there is a change in the phone or phone available
- Work on both Insert and update Contact
- Test Class below with 100% Coverage
Test ClassPlease use and let me know how it goes
All Answers
This is a simple and easy code to understand for new salesforce developer.
trigger UpdateAccountPhoneNumberTrigger on Contact (before update) {
Set<id> IdCollect = new Set<id>();
For(Contact con :Trigger.New){
If (con.Phone != null){
IdCollect.add(con.AccountId);
}
}
List<Account> acList = new List<Account>();
acList =[Select Id,Phone from Account Where Id IN:IdCollect];
//using simple map to put contact phone number
Map <Id, string> conmap = new Map <Id, string>();
for(Contact c : trigger.New){
conmap.put(c.AccountId , c.Phone);
}
if(acList!=null){
for(Account ac : acList ){
ac.Phone = conmap.get(ac.Id);
}
}
if(acList.size()>0){
Update acList;
}
}
Please mark it as best Answer if you find it helpful.
Thank You
Ajay Dubedi
optimized, efficient, less number of lines and error less.
- Took care of null values
- Only works when there is a change in the phone or phone available
- Work on both Insert and update Contact
- Test Class below with 100% Coverage
Test ClassPlease use and let me know how it goes