function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Allister McKenzie 10Allister McKenzie 10 

How would I move the SOQL queries outside of the for loop?

I have tried several times but everything I try gives an error.  How would I rewrite this to avoid hitting limits.
 
trigger taskTrigger on Task (after insert, after update) {

    List<Messaging.SingleEmailMessage> atm = new List<Messaging.SingleEmailMessage>();  
    for(task t : Trigger.new){
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();       
        if(t.Status == 'Completed' && t.Type == 'Executive Call') {
            
            List<AccountTeamMember> recips = new List<AccountTeamMember>(
                [SELECT UserId 
                 FROM AccountTeamMember 
                 WHERE AccountId = :t.AccountId]);

            Contact c = [SELECT Name FROM Contact WHERE Id = :t.WhoId];
            Account a = [SELECT Name FROM Account WHERE Id = :t.WhatId];
            String taskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + t.Id;

            String body = '<b>Executive Sponsor:</b><br/>' + '  ' + t.owner_read__c;
            body += '<br/><br/>';
            body += '<b>Contact:</b><br/>' + '  ' + c.Name;
            body += '<br/><br/>';
            body += '<b>Account:</b><br/>' + '  ' + a.Name;
            body += '<br/><br/>';
            body += '<b>Description:</b><br/>' + t.Description;
            body += '<br/><br/>';
            body += taskURL;  
            
            System.debug('body = '+body);
            mail.setSenderDisplayName('Salesforce System');
            mail.setUseSignature(false);
            mail.setBccSender(false);
            mail.setSaveAsActivity(false);
            mail.setSubject('The Executive Sponsor on this account made a call');
            mail.setHtmlBody(body);
            
            for(AccountTeamMember rid : recips){
                mail.setTargetObjectId(rid.UserId);
                
            // if Sent_Mail__c is null then change to zero then add email count else add email count
                if(t.Sent_Mail__c == null) {
                    t.Sent_Mail__c = 0;
                }
                t.Sent_Mail__c = t.Sent_Mail__c + 1;
            }
        }
        
        atm.add(mail);
    }
    
    Messaging.sendEmail(atm);
}

 
Venkat PolisettiVenkat Polisetti
You need to bulkify your triggers. This is not the correct way to write a trigger.

Read:

https://developer.salesforce.com/page/Best_Practice%3A_Bulkify_Your_Code
http://blog.jeffdouglas.com/2011/01/06/fun-with-salesforce-collections/

Hope this helps,
Venkat