For Loop within For Loop.How to avoid such situation:
I have a requirement where I am updating Parent Object(NCR__c) Status Value based on the Status of Child object(NCR_Task__c) Value.
Scenario 1: If a Parent has multiple child records and if any of the Child Record Status is Open, Parent Value should Set to Open.
Scenario 2: If a Parent has multiple child records and if any of the Child Record Status is Closed & None of the Child Record Status is Open,Parent Value should set to Closed.
Scenario 3: If a Parent has multiple child records and if all Child Records Status is Cancelled,Parent Value should set to Cancelled.
To Achive the functionality,I have written below code After Inser,After Update,After Delete of Child Records which is working fine:
public void ncrStatusAutoUpdate(List<SObject> newItems,Map<Id,SObject> oldItems){
try{
NCR__c ncrObj;
List<NCR__c> nrcListToBeUpdated = new List<NCR__c>();
Set<String> ncrListId = new Set<String>();
Set<String> ncrTaskListId = new Set<String>();
List<String> allNcrStatus= new List<String>();
for(SObject newObj :newItems){
NCR_Task__c newNCRTaskObj = (NCR_Task__c)newObj;
NCR_Task__c oldNCRObj = null;
if(newNCRTaskObj.Id!=null && oldItems!=null) {
oldNCRObj = (NCR_Task__c)oldItems.get(newNCRTaskObj.Id);
}
if(newNCRTaskObj.NCR__c!=null){
ncrListId.add(newNCRTaskObj.NCR__c);
}
}
List<NCR__c> nrcList = [SELECT Id,(SELECT Id, status__c FROM NCR_Tasks__r) FROM NCR__c WHERE ID IN :ncrListId];
for (NCR__c ncr : NrcList){
for(NCR_Task__c tasks: ncr.NCR_Tasks__r) {
allNcrStatus.add(tasks.Status__c);
}
if((allNcrStatus.contains('Open')) || (allNcrStatus.contains('In Progress'))){
ncr.NCR_Status__c='Open';
}
else if(allNcrStatus.contains('Closed')){
ncr.NCR_Status__c='Closed';
}
else {
ncr.NCR_Status__c='Cancelled';
}
nrcListToBeUpdated.add(ncr);
}
if(nrcListToBeUpdated.size()>0){
update nrcListToBeUpdated;
}
}
catch(exception ex){
system.debug('Exception in ncrStatusAutoUpdate and error is--->'+ex);
}
}
If You can see in the above code, there is a situation where I have to Use For Loop within For Loop and it is necessary otherwise my functionlity does not work as expected.
I want to know if it is valid to Use For Loop with For Loop?
As per my knowledge if I use For Loop within For Loop,it unnecessary increases CPU time Limit which might result in CPU Time Limit exception.
I have tried to written a logic under one for loop but the functionlity breaks.
Please Do Suggest if I can modify the same code by avoiding for loop within for loop...