I have 2 objects Timecard (pse__Timecard_Header__c
) and Periods (c2g__codaPeriod__c
).
There is a lookup field in Timecard Period__c
which is related to Period.
From Timecard, I need
end date pse__End_Date__c
and company id (lookup field) pse__Project__r.pse__Region__r.ffpsai__OwnerCompany__r.Id
From Periods, I need
start date c2g__StartDate__c
and owner company c2g__OwnerCompany__c
.
The idea is here to compare these fields i.e.
-
end date(timecard) = start date (period) and
-
company id(timecard) = owner company (period)
I am stuck at the last step as how to compare these values and if they are matched then assign it to the respective fields.
trigger Timecard on pse__Timecard_Header__c (after insert) {
List<pse__Timecard_Header__c> tc_list = [select Id, pse__End_Date__c, pse__Project__r.pse__Region__r.ffpsai__OwnerCompany__r.Id
from pse__Timecard_Header__c
where Id IN :Trigger.newMap.KeySet()];
system.debug('TC_LIST: ' + tc_list);
Set<Date> tc_set = new Set<Date>();
for (pse__Timecard_Header__c tcdate: tc_list)
{
Date aDate = tcdate.pse__End_Date__c.toStartOfMonth();
tc_set.add(aDate);
}
Set<String> tc_setofId = new Set<String>();
for (pse__Timecard_Header__c tcId: tc_list)
{
String s = tcId.pse__Project__r.pse__Region__r.ffpsai__OwnerCompany__c;
tc_setofId.add(s);
}
List <c2g__codaPeriod__c> periodDetails = [Select Id, c2g__StartDate__c,c2g__EndDate__c, c2g__OwnerCompany__c, c2g__Closed__c
from c2g__codaPeriod__c
where c2g__StartDate__c IN: tc_set
and c2g__OwnerCompany__c IN: tc_setofId];
for (pse__Timecard_Header__c timecardCompare: tc_list){
for (c2g__codaPeriod__c periodCompare: periodDetails){
//if
//to do comparison here
}
}
}
Best Answer
Your logic is incorrect and you are performing necessary queries as well as storing them in a way that make your code very difficult to process the record.
In the below code I have created a set of period record IDs.
The I create a map of those periods.
This allows you to cycle through the timecard headers and quickly access the associated period record and compare the values: