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
Ckevin1984Ckevin1984 

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;
        }
    }       
}

 

NaishadhNaishadh
Which timesheet record you want to update? latest one or first one.
Ckevin1984Ckevin1984
Each timesheet record should be updated. In each timesheet it contains the Hours__c and the Total_Hours__c which accumulated all the hours till the latest one.
NaishadhNaishadh
It is bit tricky. First you need update current one and then update rest one using @future method.
Ckevin1984Ckevin1984
I am newer to the Apex coding, can you please explain the @future method in a more detailed way? and is there any possible to make some changes in my code to realize this function, this will make more sense for me. Thanks in advance.
NaishadhNaishadh
just post me your entire code. I will update it and send you back.
Ckevin1984Ckevin1984

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;
        }
    }       
}

 

MiddhaMiddha

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