-1

I am hitting the governor limits on Event object and I need to change some lines in my Apex Class to avoid SOQL statements in For Loops. I got this affirmation from the support. Someone could help me to rewrite this method ? Many thanks in advance for your help.

edit 26/06 many thanks for your answers! sorry the Apex class was far so long and I just put the method I needed to change, I put the entire Apex Class,maybe hou will see better where I need to change the for loop.it is for Events:

public class Event_Ext {
/**********************************************************
    Event controller extensions, used to display two APEX
    driven Related lists on Event View and Send Mass Email
    to Invitees on click of "Send Visit Report" button on Event.
    RList 1. Event Invitees that are Amcor Employees
    Rlist 2. Event Invitees that are Non-Amcor Employees  

@Patrick Bulacz, Hallman and Associates
************************************************************/

// Declare Event Object and Attendee List Variables
private final Event myEvent;
public final Event myEvent1;
private Set<String> Contacts;
private Set<String> Leads;
private Set<String> Users; 
private final List<EventRelation> Attendees;
private  List<Employee> Employees = new List<Employee>();
private  List<Employee> nonEmployees = new List<Employee>();
private  List<Employee> EmailList = new List<Employee>();  
List<attachmentwrapper> attachmentList = new  List<attachmentwrapper>();
List<Attachment> attachmentToSend= new List<Attachment>();
List<Attachment> selectedAttachments = new  List<Attachment>();
String e1;


private Event theEvent;
private Event_Map__c theMap;
// Checkbox for checkall
public Boolean selectAll;
// Id Holder for Visual Force PolyMorphic lookup Field
public String IdHolder;
// Error Message
public String Err = '';

// list complete
public Boolean Complete = false;
 public PageReference redirect2(string str)
    {     
    PageReference r= new PageReference(str);
      r.setRedirect(true);
        return r;
    }
    // Initiate Attendee and Event Variables based on Event in Question
    public Event_Ext(ApexPages.StandardController stdController) { 

   //  String eventI=ApexPages.currentPage().getParameters().get('newid');  
  //   if(eventI.length()>8){
   //  string str= 'https://c.cs4.visual.force.com/apex/eventview?id='+eventI;
   //  redirect2(str);
   //  }else {
    // String eventI=ApexPages.currentPage().getParameters().get('newid');


  //  this.myEvent1 = (Event)stdController.getRecord();
    ID str=ApexPages.currentPage().getParameters().get('newid');
    ID str1=ApexPages.currentPage().getParameters().get('id');
      System.debug(str1+'############'+str);
   // if(str != null && str1 != null)
   if(str1 != null)
    {
      myEvent=[Select id from Event where id=:str1 ALL ROWS];
      system.debug('ID>>>>>>'+myevent.id);
      // Select attendees based on Event ID

//update LDR 17/01 The EventRelation object replaces the EventAttendee object - (www.salesforce.com/us/developer/docs/api/index_CSH.htm)
//Attendees = [select Attendee.FirstName, Attendee.LastName, AttendeeId from EventAttendee where EventId =: myEvent.Id ALL ROWS];
     Attendees = [select Id,Relation.Name from EventRelation where EventId =: myEvent.id ALL ROWS ];
     System.debug('##Attendees =##'+Attendees);

     // system.debug('Event id '+eventI);

     //  Attendees = [select Attendee.FirstName, Attendee.LastName, AttendeeId from EventAttendee where EventId =: eventI ALL ROWS];


  // Attendee Id Field of Attendees Object is Polymorphic and can be a reference to either
  // Leads / Contacts / Users so we need to seperate Id's from the List as we cannot
  // Traverse the relationship as we can in other objects

  // Create list of only unique Contacts from EventAttendees List
  Contacts = UniqueIds('003');
  // Create list of only unique Leads from EventAttendees List
  Leads = UniqueIds('00Q');
  // Create list of only unique Users from EventAttendees List
  Users = UniqueIds('005');
  // Create Employees and Non-Employees Related Lists
  CreateLists();
  redirect1();
//  }
}
}


 public PageReference redirect1()
/*LDR 25/03/2013 preventing from usage of hard-coded url :
Pagereference page = new Pagereference('/apex/MyFirstPage?id='+eid);
page.setRedirect(true);
return page;
*/

{    

 String eventId=ApexPages.currentPage().getParameters().get('newid');
 String eid=ApexPages.currentPage().getParameters().get('id');
 string str;
 System.debug('#######'+eventId+'@@@@@@@'+eid);
   // if((eid.length()<6) && (eventId.length()>10))
   if(eid.length()>10)
    {
        str='/apex/eventview?id='+eid; 
        //prod : str=/apex/eventview?id='+eid;    
        system.debug(str);     
      }
PageReference r= new PageReference('/apex/eventview?id='+eid);
  r.setRedirect(true);
  //System.debug('##str=https://c.cs4.visual.force.com/apex/eventview?id=+eventId =##'+str);
  //    return null;
        return r;

}   

public String replaceStr(String s){
   if(s==null) s='';
   return s.replace('&', '%26');
}

// update the related to on this event
public PageReference updateRelatedTo(){
  Event theEvent1 = [select Id, IsRecurrence, RecurrenceActivityId, What.Name, WhatId, WhoId, Who.Name, StartDateTime, EndDateTime, DisplayDateStart__c, DisplayDateEnd__c, DisplayRelatedTo__c, DisplayRelatedWho__c,Business_Group__c from Event where Id =: myEvent.Id ALL ROWS];
  List<Event> theEvents = new List<Event>();
  if(theEvent1.RecurrenceActivityId != null){
    theEvents = [select Id, IsRecurrence, RecurrenceActivityId, What.Name, WhatId, WhoId, Who.Name, StartDateTime, EndDateTime, DisplayDateStart__c, DisplayDateEnd__c, DisplayRelatedTo__c, DisplayRelatedWho__c,Business_Group__c from Event where RecurrenceActivityId =: theEvent1.RecurrenceActivityId ALL ROWS];
  }

  system.debug('HOW MANY EVENTS = '+theEvents.size());

  if(theEvents.isEmpty()){
    theEvents.add(theEvent1);
  }

  for(Event theEvent:theEvents){

  String startd = theEvent.DisplayDateStart__c;
  String endd = theEvent.DisplayDateEnd__c;
  String To = theEvent.DisplayRelatedTo__c;
  String Who = theEvent.DisplayRelatedWho__c;

  // update the event with the correct related to field values
  if(theEvent.WhatId != null){
      if(String.ValueOf(theEvent.WhatId).startsWith('006')){
        Opportunity o = [select Name, Account.Name from Opportunity where Id=: theEvent.WhatId ALL ROWS];
        system.debug('What.Name = '+o.Name);
        theEvent.DisplayRelatedTo__c = o.Name + ', ' + o.Account.Name;
        system.debug('The Event DisplayRelatedTo__c 006: '+ theEvent.DisplayRelatedTo__c);

      }
      else if(String.ValueOf(theEvent.WhatId).startsWith('800')){
        Contract c = [select Contract_Name_Region_Location__c, Account.Name from Contract where Id=: theEvent.WhatId ALL ROWS];
        system.debug('What.Name = '+c.Contract_Name_Region_Location__c);
        theEvent.DisplayRelatedTo__c = c.Contract_Name_Region_Location__c + ', ' + c.Account.Name;
        system.debug('The Event DisplayRelatedTo__c 800: '+ theEvent.DisplayRelatedTo__c);

      }
      else{
        Account a = [select Name from Account where Id=: theEvent.WhatId ALL ROWS];
        system.debug('What.Name = '+theEvent.Who.Name);
        theEvent.DisplayRelatedTo__c = a.Name;
         system.debug('What.Name theEvent.DisplayRelatedTo__c = '+theEvent.DisplayRelatedTo__c);

      }
    }
    else if(theEvent.WhatId == null){theEvent.DisplayRelatedTo__c = '';}

    if(theEvent.WhoId != null){
      if(String.ValueOf(theEvent.WhoId).startsWith('00Q')){
        Lead l = [select Name, Company from Lead where Id=: theEvent.WhoId ALL ROWS];
        system.debug('Who.Name = '+l.Name);
        theEvent.DisplayRelatedWho__c = l.Name + ', ' + l.Company;
        system.debug('Who.Name 00Q theEvent.DisplayRelatedWho__c = '+theEvent.DisplayRelatedWho__c);

      }
      else if(String.ValueOf(theEvent.WhoId).startsWith('003')){
        Contact c = [select Name, Account.Name from Contact where Id=: theEvent.WhoId ALL ROWS];
        system.debug('Who.Name = '+c.Name);
        theEvent.DisplayRelatedWho__c = c.Name + ', ' + c.Account.Name;
        system.debug('Who.Name 003 theEvent.DisplayRelatedWho__c = '+theEvent.DisplayRelatedWho__c);

      }
    }
    else if(theEvent.WhoId == null){theEvent.DisplayRelatedWho__c = '';}

    //Update dates for Event
    if(theEvent.StartDateTime != null){theEvent.DisplayDateStart__c = theEvent.StartDateTime.format();}
    if(theEvent.EndDateTime != null){theEvent.DisplayDateEnd__c = theEvent.EndDateTime.format();}


    if(theEvent.DisplayDateStart__c == startd && theEvent.DisplayDateEnd__c == endd && theEvent.DisplayRelatedTo__c == to && theEvent.DisplayRelatedWho__c == Who){
    }

    else{
      update theEvent;
    }
  }
  return null;
}

// Return attachments List
public Boolean getComplete(){
  return Complete;
}

// Return Amcor Employees List
public List<Employee> getEmployees(){
  return Employees;
}

// Return Amcor Non-Employees List
public List<Employee> getnonEmployees(){
  return nonEmployees;
}


// Return Amcor Non-Employees List Boolean True if List is Empty, False otherwise
public Boolean getnESize(){
  return nonEmployees.isEmpty();
}

// Return Amcor Employees List Boolean True if List is Empty, False otherwise
public Boolean getESize(){
  return Employees.isEmpty();
}

// Return Errors if Any
public String getErr(){
  return Err;
}

// Return Concatenated Lists for Email Send
public List<Employee> getEmailList(){
  if(EmailList.isEmpty()){
      EmailList.addAll(Employees);
      EmailList.addAll(nonEmployees);
  }
  return EmailList;
}

// Set Email List
public void setEmailList(List<Employee> eEmail){
  this.EmailList = eEmail;
}   

// return Id Holder for Visual Force Page Lookup Field
public String getIdHolder(){
  return IdHolder;  
}

// set Id Holder for Visual Force Page Lookup
public void setIdHolder(String sId){
  this.IdHolder = sId;
} 

// return select All checkbox
public Boolean getselectAll(){
  return selectAll;  
}

// set Id Holder for Visual Force Page Lookup
public void setselectAll(Boolean eAll){
  this.selectAll = eAll;
}

// return list of Unique Ids within EventAttendee list
public Set<String> UniqueIds(String ObjType){
  // Create a new Unique Set of Ids
  Set<String> Ids = new Set<String>();   
  //ldr EventAttendee /EventRelation Loop through EventAttendees and adding records to set based on ObjType String passed as parameter
  for (EventRelation thisAttendee: Attendees) 
  {
    if(Ids.contains(thisAttendee.RelationId) && String.ValueOf(thisAttendee.RelationId).startsWith(ObjType))
    {continue;
    }
    else if(String.ValueOf(thisAttendee.RelationId).startsWith(ObjType))
    {
    Ids.add(thisAttendee.RelationId);
    }
  }
  return Ids;
}

// Create Lists for Employees and Non Employees
public void CreateLists(){
  // Select required SObject fields within designated Sets
  List<Contact> c = [select Id, Account.Name, FirstName, LastName, Title, Email, Phone, RecordType.Name from Contact where Id IN: Contacts ALL ROWS];
  List<User> u = [select Id, FirstName, LastName, Title, Email, Phone from User where Id IN: Users ALL ROWS];
  List<Lead> l = [select Id, FirstName, LastName, Title, Email, Company, Phone from Lead where Id IN: Leads ALL ROWS];


  // Loop through contacts adding to either Employees or Non-Employees based on Record Type
  for(Contact thisC:c){
    if(thisC.RecordType.Name == 'Amcor Personnel' && thisC.Account.Name == 'Amcor Ltd'){

      Employees.add(new Employee(thisC.Id, thisC.FirstName, thisC.LastName, thisC.Email, thisC.Phone, thisC.Title, 'Amcor Ltd', thisC.RecordType.Name, false, 'Yes'));
    }
    else{

      nonEmployees.add(new Employee(thisC.Id, thisC.FirstName, thisC.LastName, thisC.Email, thisC.Phone, thisC.Title, thisC.Account.Name, 'NonP', false, 'No'));
    }
  }
  // Loop through users adding to Employees (assumes all users are internal employees)
  for(User thisU:u){

   System.debug('##########Value of thisU====>'+thisU);
    Employees.add(new Employee(thisU.Id, thisU.FirstName, thisU.LastName, thisU.Email, thisU.Phone, thisU.Title, 'Amcor Ltd', 'Amcor Personnel', false, 'Yes'));
  }
  // Loop through leads adding to Non-Employees (assumes all leads are not employees)
  for(Lead thisL:l){
  System.debug('##########Value of thisL====>'+thisL);
    nonEmployees.add(new Employee(thisL.Id, thisL.FirstName, thisL.LastName, thisL.Email, thisL.Phone, thisL.Title, thisL.Company, 'NonP', false, 'No'));
  }
}

// Return User to the Event View Page on Cancel
public PageReference cancel(){
   ID str=ApexPages.currentPage().getParameters().get('id');
   // Event myEvent3=new Event();
      if(str != null )
    {
         PageReference pageRef = new PageReference('/'+ str);
         pageRef.setRedirect(true);
          return pageRef;
           //   this.myEvent = (Event)stdController.getRecord();
       // myEvent3=[Select id from Event where id=:str ALL ROWS];
    }
    else
    return null;
}

// Build Queries for the Event and Event Map Object
public void BuildQueries(Map<String, Schema.SObjectField> emSMap, Map<String, Schema.SObjectField> evSMap){
  // Initialise variables that will hold the Field Names for eact object
  String evQuery = '';
  String emQuery = '';

  // Start a counter to account for Fence Posts (i.e select field1, field2, field3, from Sobject)
  Integer count = 0;

  // Cycle through Fields KeyMap and create a query string of Fields
  for(String thisKey:emSMap.keySet()){
    if(count == emSMap.size()-1){emQuery += emSMap.get(thisKey);}
    else{emQuery += emSMap.get(thisKey) + ', ';}
    count++;
  }

  // reset counter to account for Fence Posts
  count = 0;

  // Cycle through Fields KeyMap and create a query string of Fields
  for(String thisKey:evSMap.keySet()){
    if(count == evSMap.size()-1){evQuery += evSMap.get(thisKey);}
    else{evQuery += evSMap.get(thisKey) + ', ';}
    count++;
  }

  // Get the only Event Map Record in Existence along with all it's fields
  theMap = Database.query('select ' + emQuery + ' from Event_Map__c limit 1');
  // Convert the ID to a String for a simple query
  String id = myEvent.Id;
  // Assign the Event in Question
  theEvent = Database.query('select ' + evQuery + ' from Event where Id=\''+id+'\' LIMIT 1');
}

// Send an email template to be parsed and have Curly Bracket Strings Replaced replaced.
public String ReplaceStr(String tmp, Map<String, Schema.SObjectField> sMap){
  // Set a temporary string as '' so we have no nulls
  String tmpStr = '';

  // Loop through key map set for an event map
  for(String thisKey:sMap.keySet()){
    // add curly bracket syntax that appears in templates
    tmpStr = '{!Event_Map__c.'+sMap.get(thisKey)+'}';
    // check if template contains the curly bracket syntax for the variable in question
    if(tmp.contains(tmpStr)){
       // Try catch some exceptions if the Field Maps do not align.
       try{
         // replace it with '' if null otherwise replace the curly bracket syntax with
         // the field value
         if(String.ValueOf(theEvent.get(String.ValueOf(theMap.get(thisKey)))) == null){tmp = tmp.replace(tmpStr, '');}
         else{tmp = tmp.replace(tmpStr, String.ValueOf(theEvent.get(String.ValueOf(theMap.get(thisKey)))));}
       }
       catch(Exception e){
         // Throw an Error
         return 'error';
       }
    }
  }
  return tmp;
}


  public List<attachmentwrapper> getAttachments()
  {

   ID strsfdc=ApexPages.currentPage().getParameters().get('id');
   ID eventIdsfdc=ApexPages.currentPage().getParameters().get('newid');
   System.debug('#########'+strsfdc+'$$$$$$$$$'+eventIdsfdc);

   if(strsfdc != null)
    {
       for(Attachment t : [select ParentId, Id, Name from Attachment where ParentId =: strsfdc ALL ROWS] )
      {
        System.debug('$$$$$$$$$$$$$$$$Value of T==='+t);

            attachmentList.add(new attachmentwrapper(t));

      }
       System.debug('size of attachment'+attachmentList.size());
      return attachmentList;

   }
    else
     return null;
     //attachmentList.IsPrivate = true;

  }



  public PageReference getSelected()
  {
     selectedAttachments.clear();
      for(attachmentwrapper attwrapper : attachmentList)
      {
        if(attwrapper.selected == true)
        selectedAttachments.add(attwrapper.att);

      }
        return null;
  }

  public List<Attachment> GetSelectedAttachments()
  {
      if(selectedAttachments.size()>0)
      {
      System.debug('###########Seelcted Attachment=======>'+selectedAttachments);
      return selectedAttachments;
      }
      else
      return null;
  }   

  public class attachmentwrapper
  {
      public Attachment att {get;set;}
      public  Boolean selected {get;set;}
      public attachmentwrapper(Attachment t)
      {
          att = t;
          selected = false;

      }
  }

// Send Mass Email to Selected Users/Contacts/Leads
public PageReference SendEmail() 
{ 
     // create an empty list to hold email addresses.
      String[] Emails = new List<String>();
      String[] toAddresses = new List<String>();
      String[] BccAddresses = new List<String>();
      String[] ccAddresses = new List<String>();
      // create holders for the body and htmlvalue of a template
      String Body = '';
      String htBody = '';
      String Subject = '';


      // Select the Email Template to be Merged.
      EmailTemplate tmplate;
      Event RTname = [Select RecordType.DeveloperName, RecipientsVisitReport__c from Event where Id =:myEvent.Id ALL ROWS];
      if(RTname.RecordType.DeveloperName == 'Galaxy_Visit_Report')
      {
        tmplate = [select Subject, Body, HtmlValue, Id from EmailTemplate where Name =: 'Special Visit Report' limit 1];
        }
       else
       {
        tmplate = [select Subject, Body, HtmlValue, Id from EmailTemplate where Name =: 'Visit Report' limit 1];
        }
      // Get the sObject describe result for the Event_Map__c object and Event object and
      // describe the fields
      Map<String, Schema.SObjectField> EM = Schema.SObjectType.Event_Map__c.fields.getMap();
      Map<String, Schema.SObjectField> EV = Schema.SObjectType.Event.fields.getMap();

      // Build our queries and set our event in question using our Field Map keysets.
      BuildQueries(EM, EV);

      // replace the curly bracket syntax with field values from the event
      Body = ReplaceStr(tmplate.Body, EM);
      htBody = ReplaceStr(tmplate.HtmlValue, EM);
      Subject = ReplaceStr(tmplate.Subject, EM);

       if(Body != 'error' && htBody != 'error')
       {
          // Create our email list from the selected recipients
          for(Employee thisE:EmailList)
          {
            if(RTname.RecordType.DeveloperName == 'Galaxy_Visit_Report')
            {
                if(thisE.EmailYes == true && thisE.Email != null && thisE.Send == 'Yes')
                {
                  Emails.add(thisE.Email);
                }
            }
              else
              {
                if(thisE.EmailYes == true && thisE.Email != null)
                {
                  Emails.add(thisE.Email);
                }

            }
          }  

        // Initialise an email object to send     
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        //Save all recipients in Recipients Visit Report   
        String allRecipients = RTname.RecipientsVisitReport__c;  
         for(String thisAddy:Emails)
            {
                if(allRecipients == ''){
                 allRecipients = thisAddy;
                 continue;
                 }

               allRecipients = allRecipients +', '+  thisAddy;   
                }                                          

            RTname.RecipientsVisitReport__c =allRecipients;
            update RTname;


// split up the addresses for greater than 10 into cc's bcc's and to's.
        Integer Count = 0;

        if(Emails.size() >10)
        {
          for(String thisAddy:Emails)
            {
                if(count<=10)
                {
                  toAddresses.add(thisAddy);

                }
                else if(count >=11 && count <= 15)
                {
                  ccAddresses.add(thisAddy);
                                      }
                else if(count >= 15 && count <= 25)
                {  
                  BccAddresses.add(thisAddy);

                }
                count++;
            }
          }

          else if(!Emails.isEmpty())
          {
            toAddresses = Emails;
          }


         /* else
          {
            toAddresses.add('test@test.com');
          }*/

        // Assign the addresses for the To lists to the mail object.   
        email.setToAddresses(toAddresses);
        if(!ccAddresses.isEmpty())
        {
          email.setCcAddresses(ccAddresses);
        }
        if(!BccAddresses.isEmpty())
        {
          email.setBccAddresses(BccAddresses);
        }
        // Assign Html and Text Body Values
        email.setHtmlBody(htBody.replace('\n', '<br/>'));
        email.setPlainTextBody(Body);
        // Set email Subject
        email.setSubject(Subject);
        //picking up existing attachements
        //Defining List to store the attachments to be sent
        List<Messaging.EmailFileAttachment> ats = new List<Messaging.EmailFileAttachment>();

         //Create a list of selected attachments
          //List<Attachment> selectedAttachments = new List<Attachment>();

          //Loop through our list of attachments and check if the selected attachment is set to true, 
          //if it is we add the attachment to the selectedattachment list
        if(selectedAttachments !=null)
          if(selectedAttachments.size()>0)

          {

            for(Attachment att : selectedAttachments)
            {
                for(Attachment attachmentToSend : [select ParentId, Id, Name,Body from Attachment where Id =: att.Id ALL ROWS])
                {
                Messaging.Emailfileattachment eff = new Messaging.Emailfileattachment();
                eff.setFileName(attachmentToSend.Name);
                eff.setBody(attachmentToSend.Body);
                ats.add(eff);
                att.Body=null;
                }
            }
          }
        // Create an email attachment

           //if()
          email.setFileAttachments(ats);
          // send it, ignoring any errors (-- testing)
          Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   

          // Redirect user to the Event View Page
          PageReference pageRef = new PageReference('/'+ myEvent.Id);
          pageRef.setRedirect(true);
          return pageRef;
        }
        else
        {
          // Redirect user to the Error Page
          PageReference pageRef = new PageReference('/apex/visitreportErr?Id='+myEvent.Id);
          pageRef.setRedirect(true);
          return pageRef;
        }
  }

 // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
  public class atAttachment {
      public Attachment attach {get; set;}
      public Boolean selected {get; set;}

      //This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
      public atAttachment(Attachment at) {
          attach = at;
          selected = false;
      }
  }


// add additional Users to the Email List
public PageReference addTo() {
  system.debug(IdHolder);
  Integer count = 0;

  // Make sure the Email List is unique
  for(Employee thisE:EmailList){
    system.debug(IdHolder + ' = ' + thisE.Id);
    if(thisE.Id.subString(0,15) == IdHolder){
      count++;
    }
  }

  // Check what type of Id has been "looked up"
  if(IdHolder.StartsWith('003') && count == 0){
    // Select relevant fields from this Id
    List<Contact> listContacts = [select Id, FirstName, LastName, Account.Name, Title, Phone, Email,HasOptedOutOfEmail, RecordType.Name From Contact where Id =: IdHolder and HasOptedOutOfEmail = false All Rows];
    if(listContacts.size()<=0){
        return null;
    }
    Contact c = listContacts[0];

    if(c.RecordType.Name == 'Amcor Personnel' && c.Account.Name == 'Amcor Ltd' ){
      EmailList.add(new Employee(c.Id,c.FirstName,c.LastName,c.Email,c.Phone,c.Title,c.Account.Name,c.RecordType.Name, true, 'Yes'));
    }

    else{
      EmailList.add(new Employee(c.Id,c.FirstName,c.LastName,c.Email,c.Phone,c.Title,c.Account.Name,c.RecordType.Name, true, 'No'));
    }       

}
else if(IdHolder.StartsWith('00Q') && count == 0){ // Select relevant fields from this Id Lead l = [select Id,FirstName, LastName, Company, Title, Phone, Email,HasOptedOutOfEmail From Lead where Id =: IdHolder and HasOptedOutOfEmail = False ALL ROWS];

    // Add this Lead to the Email List
    EmailList.add(new Employee(l.Id,l.FirstName,l.LastName,l.Email,l.Phone,l.Title,l.Company,'NonP', true, 'No'));
  }

  else if(IdHolder.StartsWith('005') && count == 0){
    // Select relevant fields from this Id
    User u = [select Id, FirstName, LastName, Title, Phone, Email From User where Id =: IdHolder ALL ROWS];
    // Add this Lead to the Email List
    EmailList.add(new Employee(u.Id,u.FirstName,u.LastName,u.Email,u.Phone,u.Title,'Amcor Ltd','Amcor Personnel', true, 'Yes'));
  }
  return null;
}

public PageReference attach() { 
  Complete = true;
  return null;    
}


// check/uncheck all recipients for sending and display
public PageReference checkAll(){
  for(Employee thisE:EmailList){
    if(selectAll == true){

      thisE.EmailYes = true;
    }
    else{
      thisE.EmailYes = false;
    }
  }
  return null;
}
}
6
  • 3
    what calls getAttachments() ? if the caller can invoke getAttachments() many times - such as in a trigger, you will hit the governor limit
    – cropredy
    Jun 25 '14 at 19:23
  • 2
    Are there any SOQL calls in the AttachmentWrapper constructor? Jun 25 '14 at 19:34
  • I don't think this method is what is causing that error.
    – dphil
    Jun 25 '14 at 19:57
  • I don't understand what the lines " if(strsfdc != null) list<attachment>" accomplish. It looks to be like that orphans the block below, but I may be missing something.
    – Jagular
    Jun 25 '14 at 20:11
  • You said you are hitting limits on Event object but I dont see any reference to Event in your code. Can you please share what limits are you specifically talking about? Jun 26 '14 at 2:49
1

You could do something like this.

List<Attachment> attachmentList{
    get{
        if( attachmentList == null || attachmentList.isEmpty() )
        {
            attachmentList = [SELECT ParentId, Id, Name from Attachment where ParentId =: strsfdc ALL ROWS];
        }
        return attachmentList;
        }
    set;  
}

Using this method, it will only query the list if it is null or empty. You can handle getting the Id's in the Constructor.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.