function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
shweta chadha 4shweta chadha 4 

Need to update the value of related to "Company" field on Task object (if it is null) based on the related to Contact field value.

Hello,

I need to write a trigger to update the value of Related to company field ( if it is null only) on the task object based on the related to contact field value. Please help me how can I achieve this.

Thanks, Shweta
Best Answer chosen by shweta chadha 4
Jolly_BirdiJolly_Birdi
Hello @Shweta

Please check the below Code:
 
trigger TaskTrigger on Task (after update) {
	for(Task newTask : Trigger.New){
		// Task.WhoId != null                      ----Checks Contact is null or not
		// ((string)Task.WhoId).startsWith('003')  ----Checks Task is related to Contact
		// Task.WhatId == null                     ----Checks the related to field is null or not
		if(Task.WhoId != null && ((string)Task.WhoId).startsWith('003') && Task.WhatId == null ){
			// Add your code as per your needs.
		}
	}
}



Please like and mark it as best answer if you find it positive.

Thanks
Jolly Birdi

All Answers

Jolly_BirdiJolly_Birdi
Hello @Shweta

Please check the below Code:
 
trigger TaskTrigger on Task (after update) {
	for(Task newTask : Trigger.New){
		// Task.WhoId != null                      ----Checks Contact is null or not
		// ((string)Task.WhoId).startsWith('003')  ----Checks Task is related to Contact
		// Task.WhatId == null                     ----Checks the related to field is null or not
		if(Task.WhoId != null && ((string)Task.WhoId).startsWith('003') && Task.WhatId == null ){
			// Add your code as per your needs.
		}
	}
}



Please like and mark it as best answer if you find it positive.

Thanks
Jolly Birdi
This was selected as the best answer
shweta chadha 4shweta chadha 4
HI Jolly,

Thank you for your reply. I do need to pre-fill the value before submitting the record. I meant need to do on before insert.

Thanks, Shweta
Jolly_BirdiJolly_Birdi
Shweta,

For this you check the below code, the changes you will made in the newTask it will automatically update the tasks values.
 
trigger TaskTrigger on Task (before insert) {
	for(Task newTask : Trigger.New){
		// Task.WhoId != null                      ----Checks Contact is null or not
		// ((string)Task.WhoId).startsWith('003')  ----Checks Task is related to Contact</b>
		// Task.WhatId == null                     ----Checks the related to field is null or not
		if(Task.WhoId != null && ((string)Task.WhoId).startsWith('003') && Task.WhatId == null ){
			// Add your code as per your needs
		}
	}
}

Please like and mark it as best answer if you find it positive.

Thanks
Jolly Birdi