+ Start a Discussion
Jon FoyJon Foy 

Need Help with Apex Trigger Code

We have two custom objects: Task_Custom__c and Timeslip__c.
Timeslip contains these fields:
"Total_Billable_Time__c" (hours)
"Related_Task__c" (a lookup on the Task_Custom__c object)

Therefore when viewing a Task, it gives a list of all related Timeslip's.  
What I want to do is have a field on the Task_Custom__c object "Billable_Time__c" which would be a summary of all "Total_Billable_Time__c" from all related Timeslips.  I can't do a rollup summary because it's a cross object reference.  Is there a way to write an apex trigger for the TimeSlip object that would update the "Billable_Time__c" field on a Task anytime a timeslip is created or updated that is related to that Task?
Geoffrey J FlynnGeoffrey J Flynn
Hi Jon,

There is, but I find this point and click package easier and more scaleable
https://developer.salesforce.com/page/Declarative_Rollup_Summary_Tool_for_Force.com_Lookup_Relationships
PaulJSPaulJS
Hi Jon - try this.  As luck would have it, I was working on something similar today.  This is based on what I was able to get working in my own org, but I admittedly have not gotten around to fully testing it, etc.  Let me know if something here doesn't work.
trigger billableTime on Timeslip__c (after insert, after update, after delete, after undelete) {
    
    Set<Id> idSet = new Set<Id>();
    
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
    	for(Timeslip__c ts : trigger.new){
            if(Trigger.isUpdate && ts.Total_Billable_Time__c != trigger.oldMap.get(ts.Id).Total_Billable_Time__c){
                idSet.add(ts.Related_Task__c);
            } else if((Trigger.isInsert || Trigger.isUndelete) && Total_Billable_Time__c != NULL){
            	idSet.add(ts.Related_Task__c);
        	}
    	}
    }    
    
    if(Trigger.isDelete){
        for(Timeslip__c ts: Trigger.old){
            idSet.add(ts.Related_Task__c);
        }
    }
    
    if(idSet != NULL){
    
    	Map<Id,Double> timeMap = new Map<Id,Double>();
    	
    	for(AggregateResult ar: [SELECT Sum(Total_Billable_Time__c) Total, Related_Task__c FROM Timeslip__c WHERE Related_Task__c IN :idSet GROUP BY Related_Task__c]){
    	    timeMap.put((Id)ar.get('Related_Task__c'),(Double)ar.get('Total'));
    	}
    	
    	List<Task_Custom__c> taskToUpdate = new List<Task_Custom__c>();
    	
    	for(Task_Custom__c tc : [SELECT Id, Billable_Time__c FROM Task_Custom__c WHERE Id ID :idSet]){
    	    tc.Billable_Time__c = timeMap.get(tc.Id);
    	    taskToUpdate.add(tc);
    	}
    
    	Update taskToUpdate;
    }    
}