I have a custom object called Inspection__c, which is a child object of the Account object. The Account object has another child object called Monthly_Quota__c, each Account has 12 records of this (one for each month of the year, each with the same month name across accounts) and Inspection__c has a lookup field that references this object. I would like a trigger on the Inspection__c object that updates the lookup by referencing the name of the Monthly Quota (i.e., January, February, etc.) on the correct account based on the date of Inspection. So for example of Account A does an inspection in February 2018, the lookup will find the 'February' monthly quota for Account A, and if Account B does an inspection in February 2018, that inspection lookup will find the 'February' monthly quota for Account B, etc. etc. The trigger I have so far is:
trigger InspectionQuotas on Inspection__c (after update) {
Set<id> AccountId = new Set<Id>();
for (Inspection__c i : Trigger.new) {
AccountId.add(i.Franchise__c);
}
Set<String> nameString = new Set<String>{'January','February','March'};
Map<String,Monthly_Quota__c> keyByLookupMap = new Map<String,Monthly_Quota__c>();
for(Monthly_Quota__c mq : [SELECT Id, Name
FROM Monthly_Quota__c
WHERE Name IN :nameString AND Account__c = :AccountId]){
keyByLookupMap.put(mq.name,mq);
}
for(Inspection__c i : trigger.new){
if(i.Inspection_Year_Month__c == '2018-01-January'){
if(keyByLookupMap.containsKey('January'))
i.Monthly_Quota__c = keyByLookupMap.get('January');
}
if(i.Inspection_Year_Month__c == '2018-02-February'){
if(keyByLookupMap.containsKey('February'))
i.Monthly_Quota__c = keyByLookupMap.get('February');
}
if(i.Inspection_Year_Month__c == '2018-03-March'){
if(keyByLookupMap.containsKey('March'))
i.Monthly_Quota__c = keyByLookupMap.get('March');
}
}
}
But it's not working. What am I doing wrong?
Inspection_Year_Month__c
? Check your if blocks whether the code enters there. I would suggest putting a debug statement -System.debug(i.Inspection_Year_Month__c );
.System.debug( datetime.now());
=>2017-12-04 22:03:14
andSystem.debug(Date.today());
=>2017-12-04 00:00:00