You need to sign in to do that
Don't have an account?
Ckevin1984
Error message of "maximum trigger depth exceeded"
Hi all,
I am a newer to apex, here is the trigger i wrote having the error message "maximum trigger depth exceeded" .
trigger TimeSheetTrigger on Timesheet__c (after delete, after insert, after update)
{
double TotalHours = 0.0;
for (Timesheet__c timeSheet: [select Id, Hours__c from Timesheet__c ])
{
TotalHours += timeSheet.Hours__c;
if(timeSheet.Hours__c != NULL)
{
timeSheet.Total_Hours__c = TotalHours;
update timeSheet;
}
}
}
Hello Ckevin1984;
In your trigger you are updating a "Timesheet__c" object at the line "update timeSheet;".
update timeSheet;
Then this cause your trigger runs again. This makes an infinite loop. That is the reason for this error.
If you remove the "after update" part from your trigger then the error will be fixed.
trigger TimeSheetTrigger on Timesheet__c (after delete, after insert)
Perhaps that was just a snapshot of your code, minimized for discussion purposes but in case not do you really want to update every timesheet in the system everytime someone saves one timesheet__c record?
I'm guessing that removing "after update" isn't going to work for you because you want this trigger to fire on update. FYI, you may also want it to fire on undelete (remove from recycle-bin).
Also, have you disqualified Roll-up Summary Formulas (calculated field type) for your solution? From what I can see in your code if your data model was changed slightly you might be able to do what you are after without a trigger.
If it turns out you need this trigger and you need it to fire on update as well, you'll have to control the recursion with static variables. Check out this section of the Apex Developer Guide for more info.
It looks working at first. But the problem happens when i try to add new records again the second time. Coz the sentences of my code
for (Timesheet__c timeSheet: [select Hours__c from Timesheet__c])
{
TotalHours += timeSheet.Hours__c;
can not go through the old records to get the Hours__c value, it only goes through the new records and accumulate the new Hours__c values. What i want are both the existing Hours__c and the new added ones. Looking forward for your help again. Thanks in advance.
what i meant it works was after i deleted the "after update" operation in my code.