+1 vote
23 views
by (163k points)

I have written a simple apex class/trigger. The before update trigger calls a handler class which does some processing (needs to set a field to a specified value). However, I have a for loop inside of the SOQL. Does anyone know how to remove this SOQL from inside the for loop that is in the apex handler? Thank you

Apex trigger calls this handler class:

public static void onBeforeUpdate( List< Opportunity > opportunities , Map<ID , Opportunity > l_old_map ){
List<Opportunity> opps2Update = new List<Opportunity>();
if(opp.Field1__c != l_old_map.get( opp.id ).Field1__c){
                    opps2Update.add(opp);
                }
if(!opps2Update.isEmpty()){
            OppHandler.setFieldValue(opps2Update);
        }

the handler apex:

public with sharing class LPP_OpportunityHandler 
{
public static void setFieldValue(List<Opportunity> opps2Update){
        for(Opportunity opp : opps2Update){
            if(opp.Field2__c == null){
                opp.Field_Status__c = 'Invalid';
            }else {
                String status = [select id, Status__c from LookUpObject_Status__c WHERE Id =:opp.Field1__c].LookupObject_Status__c;
                opp.Field_Status__c = status;
            }
        }
    }
}

1 Answer

+1 vote
by (163k points)
 
Best answer

You aggregate the values, then query, and then update.

public static void setFieldValue(Opportunity[] oppsToUpdate) {
    Map<Id, LookupObject_Status__c> lookups = new Map<Id, LookupObject_Status__c>();
    for(Opportunity record: oppsToUpdate) {
        lookups.put(record.Field1__c, null);
    }
    lookups.putAll([
        SELECT Status__c FROM LookupObject_Status__c WHERE Id = :lookups.keySet()
    ]);
    for(Opportunity record: oppsToUpdate) {
        LookupObject_Status__c status = lookups.get(record.Field1__c);
        if(status == null) {
            record.Field_Status__c = 'Invalid';
        } else {
            record.Field_Status__c = status.Status__c;
        }
    }
}
Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.
...