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
Salesforce Dev in TrainingSalesforce Dev in Training 

Apex Trigger in Tasks

Hello Developer Community,

I have a question in dealing with Apex Triggers and the Task object in Salesforce. I have had help on here thus far, and I'm just about to where I need to be, but there's a snag.
Here's my code:

trigger TaskTrigger on Task (before insert) {
    for(Task ta: Trigger.new) {
        if(ta.Task_Results__c != null && ta.Subject != ta.Task_Results__c) {
            ta.Subject += ' ('+ta.Task_Results__c + ')';
        }
    }
}

This is working great.
When creating a NEW task, if the Subject is blank, then whatever is picked from the Task Results picklist autofills into the Subject -- this is great! (it does not duplicate the Task Results)
If the NEW Subject is "Call" and the Task Result is "Inbound - HWN" then the Subject becomes "Call (Inbound - HWN)" -- this is great!
However if it's an EXISTING task with the Subject of "Call", and I try to edit the Task and select the Task Results to be Inbound - HWN, it doesn't get added to the Subject at all. The Subject stays as Call. I want to Task Results to be added (only once) to the Subject if the Task is edited and it isn't there yet.

I believe I either need another trigger to combat this or potentially change up the language.

Any help is much appreciated as I'm learning Apex currently.

sslodhi87sslodhi87
Hi,
 
trigger TaskTrigger on Task (before insert, before update) 
{
	if(Trigger.isBefore )
	{
		for(Task ta: Trigger.new) 
		{
			if(Trigger.isNew && ta.Task_Results__c != null && ta.Subject != ta.Task_Results__c) 
			{
				ta.Subject += ' ('+ta.Task_Results__c + ')';
			}
			else if(Trigger.isUpdate && ta.Task_Results__c != null && (String.isEmpty(ta.Subject) || !ta.Subject.contains(ta.Task_Results__c)))
			{
				ta.Subject += ' ('+ta.Task_Results__c + ')';
			}
		}
	}
}

Please let me know this help you