I have a requirement to check Terminated__c flag on multiple child records (lead_Custom__c) and if it is true, then update the Terminated__c flag on Parent record (contact).
Below is the apex class:
public with sharing class Lead_TerminationCheck {
public void UpdateFields(List<Lead_Custom__c> newList) {
List<Contact> updateList = new List<Contact>();
Map<id,List<Lead_Custom__c>> mapParentIDAndChild = new Map<id,List<Lead_Custom__c>>();
boolean flag;
set<Id> parenetTrue = new set<Id>();
for(Lead_Custom__c objChild : newList) {
parenetTrue.add(objChild.Contact__c);
}
for(Lead_Custom__c objChild : [select id , Terminated__c , Contact__c from Lead_Custom__c where Contact__c IN: parenetTrue] ){
if(mapParentIDAndChild.containsKey(objChild.Contact__c)) {
mapParentIDAndChild.get(objChild.Contact__c).add(objChild);
} else {
mapParentIDAndChild.put(objChild.Contact__c,new List<Lead_Custom__c>{objChild});
}
}
for(Id objId : mapParentIDAndChild.keySet()) {
flag = true;
for(Lead_Custom__c objChild : mapParentIDAndChild.get(objId)) {
if(objChild.Terminated__c == false){
flag = false;
break;
}
}
if(flag == true) {
updateList.add(new Contact(Id = objId , Terminated__c = true));
}
}
if(!updateList.isEmpty()) {
update updateList;
}
}
}
The above apex class is working only if all the child records have Termination__c as true. But, is there any way to check the parent has more than one child record and if yes, then even if any one the child record has this flag set to true, then parent's terminated flag should be updated.
Can anyone please suggest the changes to the above apex class so that I can get this done.
Thanks!