I try to write a trigger that set case status to "Closed" if thereare more than 2 cases created that same day (today) associated with the same contact. The problem is I don't want to use SOQL queries in for loops or nested for loops. I try to do it via map with a list as value, but can't get it working. I looked into this solution: Is there a way to get the list size from map<string,List<Sobject>>, but it gives me another for loop which makes it a nested for loop, which i try to prevent. Here is my code:
public without sharing class CaseStatusClosed {
public static void triggerInjection(List<Case> caseList) {
Set<Id> caseContactIdSet = new Set<Id>();
Map<Id, Contact> contactById = new Map<Id, Contact>();
//List<Case> caseAddList = new List<Case>();
Map<Id, List<Case>> caseListByContactId = new Map<Id, List<Case>>();
for(Case myCase : caseList){
if(myCase.CreatedDate == Date.Today()){
caseContactIdSet.add(myCase.ContactId);
//caseAddList.add(myCase);
if(!caseListByContactId.containsKey(myCase.ContactId)){
caseListByContactId.put(myCase.ContactId, new List<Case>());
}
caseListByContactId.get(myCase.ContactId).add(myCase);
}
}
List<Contact> contList = [SELECT Id FROM Contact WHERE Id IN :caseContactIdSet];
//Contacts related to cases Id of today
for(Case myCase : caseList){
if(caseListByContactId.get(myCase.ContactId) != null && caseListByContactId.get(myCase.ContactId).size() > 2){
myCase.status = 'Closed';
}
}
}
}