+ Start a Discussion
Luke Higgins 22Luke Higgins 22 

Batch class not updating fields

I am trying to update the Hours_Worked_Last_2_Weeks__c field on the Placement__c object through running a batch class on the related Timesheet__c object. Each Timesheet__c that meets the criteria, should add it's Total_Hours__c to it's Placement__c's Hours_Worked_Last_2_Weeks__c. I'm getting no error but the Hours_Worked_Last_2_Weeks__c is not populating.

Batch Class:

public class hfFlagB implements Database.Batchable<sObject>, Database.Stateful{
   List<Timesheet__c> tsList = [SELECT Id FROM Timesheet__c WHERE Status__c ='Approved' AND Week_Ending__c = LAST_N_DAYS:15 ];
   Set<String> tsSet = new Set<String>();
	public Database.QueryLocator start(Database.BatchableContext bc) {
     for(Timesheet__c ts : tsList){
        tsSet.add(ts.Id);
     }
        return Database.getQueryLocator('SELECT Id, Total_Hours__c, Placement__r.Hours_Worked_Last_2_Weeks__c, Placement__c FROM Timesheet__c WHERE Id IN :tsSet');
        }
   public void execute(Database.BatchableContext BC, List<Timesheet__c> a){
      for(Timesheet__c t : a){
         t.Placement__r.Hours_Worked_Last_2_Weeks__c +=  t.Total_Hours__c;   
        }
     }
   public void finish(Database.BatchableContext BC){
   }
}
Andrew GAndrew G
Hi Luke

A bit rusty on batchable classes, but I see no update/insert/upsert against the Placement object.  Could that be the cause of your issue?

Second thing I note when reading your class, if we are batching, and the query is simply against Timesheet object, are all the Timesheets to be totaled against a single Placment object, or within the 2 week period, are there Timesheets to be totalled against different Placement records?  If so, consider the use of a Map e.g.
Map<Placement_Id, List<Timesheets>>
That way you could loop a list of Placments, use a .get on the Map and loop the list of timesheets for that particular Placement record.

Regards
Andrew