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
cduncombe44cduncombe44 

Activity Count Trigger not working on Update

I have created an activity count trigger for a custom object based on a few forum posts.  I have a few custom objects, process__c, and Process_Step__c.  As you might imagine my Proccess__c is made up of 1 or more Process _Step__c.  

 

This trigger works fine for inset and for update only if you are changing the task to meet the criteria (WhatId is a process_Step__c and Status = 'Completed').  

 

It does not however work to decrement the activity count if the task is updated and no longer meets the criteria.  I know I dont account for this, I am stuck in how to check for this and how to handle it.

 

Any help would be greatly appreciated.

 

 

trigger UpdateActivityCountForProcessAndSteps on Task (after insert, after update) {    
    	
    	List<Process_Step__c> stepUpdateList=new List<Process_Step__c>();
		List<Process_Step__c> stepList=[select id, Process__c, Process__r.Activity_Count__c, Activity_Count__c from Process_Step__c];
		List<Process__c> processUpdateList=new List<Process__c>();
		
		List<AggregateResult> TasksPerStep = new List<AggregateResult>();
		TasksPerStep=[Select count(Id),WhatId, Status From Task Where id=:Trigger.new and What.Type = 'Process_Step__c' and Status = 'Completed'      group by WhatId, Status];
	
		for(Integer i=0;i<TasksPerStep.size();i++) {
			for(Process_Step__c step : stepList) {
				if(step.id==TasksPerStep[i].get('WhatId')) {
					step.Activity_Count__c = (Integer)TasksPerStep[i].get('expr0') + step.Activity_Count__c;
					step.Process__r.Activity_Count__c = (Integer)TasksPerStep[i].get('expr0') + step.Process__r.Activity_Count__c;			
					stepUpdateList.add(step);
					processUpdateList.add(step.Process__r);
				}
			}
		}		
		update stepUpdateList;
		update processUpdateList;

}

 

Thanks in advance,

 

Chris