I'm trying to write a trigger that will update specific fields on child records if certain criteria are met on the parent object. I have two custom objects Sesaco_Contract__c (Master) and Receiving__c (Child). I have the following fields
Sesaco_Contract__r.Amount_Paid__c
Receiving__r.Include_in_Settlement__c (checkbox)
Receiving__r.Paid__c (checkbox)
On the Parent object (Sesaco_Contract__c) I want to check to see if "Amount_Paid__c" is changed and if it is, change "Paid__c" to True for any Receiving (child) record where "Include_in_Settlement__c" is True. I would also like to be able to set "Include_in_Settlement__c" to False as well. So, if a payment is made on the master record, any child records that have been set to include in a settlement have the "paid" cb ticked and the include in settlement cb unticked.
I think I have something that is close to what is needed but the console isn't letting me save due to the Receiving__r in the FROM part of my query.
Any help or suggestions are greatly appreciated.
trigger markRecRptPaid on Sesaco_Contract__c (after update) {
Set<ID> maids = new Set<ID>();
Sesaco_Contract__c ma = [Select Id, Amount_Paid__c From Sesaco_Contract__c Where Crop_Year__c = 'system.Date.year.today()'];
for(Sesaco_Contract__c sc : Trigger.new){
// Access old record
Sesaco_Contract__c oldMA = Trigger.oldMap.get(SC.Id);
if(oldMA.Amount_Paid__c != sc.Amount_Paid__c){
maids.add(sc.Id);
}
}
List<Sesaco_Contract__c> updatedMA = [SELECT Id, Amount_Paid__c, (Select Id, Include_in_Settlement__c, Paid__c from Receiving__r) FROM Sesaco_Contract__c WHERE Id in :maids];
List<Receiving__c> recrptUpdate = new List<Receiving__c>();
for (Sesaco_Contract__c sc : updatedMA){
// Loop through each Related Receiving record
for(Receiving__c rec : sc.Receiving__c){
if(rec.Include_in_Settlement__c = True){
rec.Include_in_Settlement__c = false;
rec.Paid__c = True;
recrptUpdate.add(rec);
}
}
}
update recrptUpdate;
}
Best Answer
below is my trim down approach -
I don't think if(rec.Include_in_Settlement__c = True) is necessary. Please test this solution in your environment.