+ Start a Discussion
VRKVRK 

update new Task & Event phone number based on Contact Phone number by using Trigger

Hi 
Scenario : when i create new Task / Event , then phone number field value populate from related to Contact Object Phone field.
For example :
I have Contact ' Test Contact ' and phone number is '99999999'.
When i create any Task /  Event, then Test Contact phone number is display as '99999999'.

Thanks
VRK
Abhishek BansalAbhishek Bansal
Hi VRK,

You can use the below code:
trigger updatePhone on Task (before insert) {
    Set<Id> condIds = new Set<Id>();
	
	for(Task newTask : trigger.new) {
		if(newTask.WhoId != null && String.valueOf(newTask.WhoId).startsWith('003')) {
			condIds.add(newTask.WhoId);
		}
	}
	
	if(condIds.size() > 0) {
		Map<Id, Contact> mapOfContacts = new Map<Id, Contact>([Select Id, Phone from Contact where Id IN: condIds]);
		for(Task newTask : trigger.new) {
			if(newTask.WhoId != null && String.valueOf(newTask.WhoId).startsWith('003') && mapOfContacts.containsKey(newTask.WhoId)) {
				//Replace Test_Contact_Phone_Number__c with API name of the field
				newTask.Test_Contact_Phone_Number__c = mapOfContacts.get(newTask.WhoId).Phone;
			}
		}	
	}
}

Please take care of the syntax errors and API name of the fields. Let me know if there is an issue.

Thanks,
Abhishek Bansal.
VRKVRK
Thank you Abhishek,
What about Old data ?
Is this code works for Old data also ? i mean old Tasks & events also update the  Contact's phone number ?
or we need to add any additional code ?
Thanks


 
Abhishek BansalAbhishek Bansal
Hi,

This will work only for new records, for old data you need to use a batch class. This batch class will run for one time and will update all the old data.
If your original questions is anwered than please close this question by choosing a best answer. You can open a new question for the batch class.

Thanks,
Abhishek Bansal.
VRKVRK
I am looking for  beforeInsert & beforeUpdate methods for this scenarios..
can you pls share code ...& and also TestClass also for the same
 
Abhishek BansalAbhishek Bansal
Hi ,

We are here to give you some guidance not to provide the complete solution. Please follow the below links to understand how the triggers works and how to write the test classes:
https://trailhead.salesforce.com/en/content/learn/modules/apex_triggers/apex_triggers_intro
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm

If you still want the complete solutions than please contact me. I can help you.
Gmail: abhibansal2790@gmail.com
Skype: abhishek.bansal2790

Thanks,
​​​​​​​Abhishek Bansal.