You need to sign in to do that
Don't have an account?
GC_00001
Apex Code - moving a list outside a for loop in trigger
I need to make the following piece of code work (within a trigger) for mass case updates. It works fine for when one case is updated but I know that the List<Account>.. within the for loop gives a too many soql queries message when I am mass updating. How do I move this outside the for loop but still be able to get hold of the relevant field from the associated account I want to update the case with? (I appreciate this is probably a basic thing but this is my first foray into "bulkifying").
} else if (Trigger.isUpdate && Trigger.isBefore) {
List<Case> updatedCases = Trigger.New;
Map<Id,Case> oldMap = Trigger.oldMap;
Set<Id> machineIdSet = new Set<Id>();
for(Case updatedCase: updatedCases)
{
if(updatedCase.AssetId != null)
{
machineIdSet.add(updatedCase.AssetId);
}
if(updatedCase.ClosedDate == null)
{
if(updatedCase.AccountId != null)
{
List<Account> Account = [SELECT id,Country__c, Region__c, Distributor__r.Name, US__c FROM Account WHERE id = :updatedCase.AccountId];
for(Account ac : Account)
{
if (updatedCase.Account_Country__c <> ac.Country__c)
{
updatedCase.Account_Country__c = ac.Country__c;
}
}
}
} else if (Trigger.isUpdate && Trigger.isBefore) {
List<Case> updatedCases = Trigger.New;
Map<Id,Case> oldMap = Trigger.oldMap;
Set<Id> machineIdSet = new Set<Id>();
for(Case updatedCase: updatedCases)
{
if(updatedCase.AssetId != null)
{
machineIdSet.add(updatedCase.AssetId);
}
if(updatedCase.ClosedDate == null)
{
if(updatedCase.AccountId != null)
{
List<Account> Account = [SELECT id,Country__c, Region__c, Distributor__r.Name, US__c FROM Account WHERE id = :updatedCase.AccountId];
for(Account ac : Account)
{
if (updatedCase.Account_Country__c <> ac.Country__c)
{
updatedCase.Account_Country__c = ac.Country__c;
}
}
}
All Answers