+ Start a Discussion

Basic Apex trigger question

I'm new to Apex coding, so I have what is probably a really simple question about getting a trigger to update a field.  I have a custom object called Timed Item that relates to a case, so I want to be able to have a case field that shows the total of all Timed Items in a case's related list.  I figure the way to do this is create a trigger that fires after insert of the timed item, taking the amount of the Time field from the newly-created Timed Item and updating the Total Hours field of the case by adding the amount of the Time field to the total.  I think I have to do something like this, but I'm not sure:



trigger add_time_to_total on vftimer__TimedItem__c (after insert) {


vftimer__TimedItem__c time = ???

Case c = time.vftimer__Case__c

c.Total_Hours_Logged__c += time.vftimer__Time__c

insert c



What do I need to put into the ??? to make the "time" object grab the data from the Timed Item which was just created?  And do I have everything else correct, updating the Total Hours Logged field with the amount of the Timed Item?


Thanks for the help, anybody that bothers to respond!


Before we jump into Apex trigger to solve this, I am curious if you could use a Roll up Summary field to solve this problem.


Is the TimedItem__c object a Master-Detail relationship to Case?


If so, you could try to create a new custom field of type "Roll Up Summary" data type, and SUM the  related Timer fields.


More info on Roll Up Summary fields: https://na3.salesforce.com/help/doc/user_ed.jsp?section=help&loc=help&target=fields_about_roll_up_summary_fields.htm%23topic-title


The Timed Item object is a managed object, so I'm not able to include it in a master-detail relationship.  That would definitely be the easier way to resolve the issue...