You need to sign in to do that
Don't have an account?
Asking for Help
Hi all,
I have a object named Timesheet, it has two fields : TotalHours and Hours. What i want is after i add a new Timesheet and enter numbers in the Hours field and click save button, the TotalHours field will show the accumulated Hours till now. But the code below doesn't work properly. Anyone helps me, thank a lot .
trigger TimeSheetTrigger on Timesheet__c (after delete, after insert)
{
double TotalHours = 0.0;
for (Timesheet__c timeSheet: [select Hours__c from Timesheet__c ])
{
TotalHours += timeSheet.Hours__c;
if(timeSheet.Hours__c != NULL)
{
timeSheet.Total_Hours__c = TotalHours;
update timeSheet;
}
}
}
Actually, this is my entire code of the trigger and i have on object named Timesheet and it contains Hours and TotalHours fields
trigger TimeSheetTrigger on Timesheet__c (after delete, after insert)
{
double TotalHours = 0.0;
for (Timesheet__c timeSheet: [select Hours__c from Timesheet__c ])
{
TotalHours += timeSheet.Hours__c;
if(timeSheet.Hours__c != NULL)
{
timeSheet.Total_Hours__c = TotalHours;
update timeSheet;
}
}
}
You can use Aggregate queries released in Spring 10 to achieve your requirement. Something like this:
AggregateResult[] groupedResults = [Select SUM(Hours__c) from TimeSheet__c];
/G