• Steve Thurston
  • NEWBIE
  • 10 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 13
    Replies
I'm stumped as to why my emails aren't being delivered from my Sandbox when I use an Apex class.  Here is what I've checked:

(I have replaced the email from actual results with 'MY EMAIL 1' and 'MY EMAIL 2', so that's not bad email values in the code.)

1) Deliverability:  Set to All email

2) Bounce management:  Both checked and unchecked

3) Test Deliverability:  Recieved all 32 emails

4)  Single message:  I need to deliver a templated email with an attachment, but just to try and see if I can get anything to work, I've commented that out and just tried to send a single email.  I copy and pasted the code off the web in an effort to make sure I'm not overlooking anything.  Here it is, copy-and-pasted straight from my class (and then masked the email):

Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
    String[] sendingTo = new String[]{'MY EMAIL ADDRESS 1'};
    semail.setToAddresses(sendingTo);
    String[] sendingToBccAdd = new String[]{'MY EMAIL 2'};
    semail.setBccAddresses(sendingToBccAdd);
    String[] sendingTocAdd = new String[]{'MY EMAIL 1'};
    semail.setCcAddresses(sendingTocAdd);
    semail.setSubject('Single Email message Example');
    semail.setPlainTextBody('Hello!!!!!!!!!!This is a test email to test single email message program');
            
try {
    system.debug('Yapa - Sending a non-template email.');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
    }
catch (exception e) {
        system.debug('Yapa - Tried to send a non-template email and got an error:  ' + e);
    }    

5)  Debug logs:  system.debug statements and try... catch

I've thrown in all sorts of debug entries.  You can see in the single message email I'm sending that I am logging both success and failure.  When I look at debug logs, the "try" statement succeeds and I can see the email in the logs.

6)  Email logs:  Nothing.  The Deliverability test shows up in the log, but none of the many, many email tests I've tried.

For testing, I've got a button on my Lead object that calls a class to send the email.  Like I said, I've got it debug logged the !*(& out of, and I've traced it working all the way to the email send in the 'try...catch', and it's working, with all the correct values, right up to the send which gives the appearance of having worked.  But the emails never show up.

Here's a sample from the log:

15:00:07.0 (68224890)|VARIABLE_SCOPE_BEGIN|[176]|semail|Messaging.SingleEmailMessage|true|false
15:00:07.0 (68286222)|VARIABLE_ASSIGNMENT|[176]|semail|"common.api.soap.wsdl.SingleEmailMessage@76bb46ad"|0xac78023
15:00:07.0 (68293666)|STATEMENT_EXECUTE|[177]
15:00:07.0 (68303142)|HEAP_ALLOCATE|[177]|Bytes:4
15:00:07.0 (68324170)|HEAP_ALLOCATE|[177]|Bytes:29
15:00:07.0 (68332788)|VARIABLE_SCOPE_BEGIN|[177]|sendingTo|List<String>|true|false
15:00:07.0 (68351056)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
15:00:07.0 (68360976)|VARIABLE_ASSIGNMENT|[177]|sendingTo|["MY EMAIL 1"]|0x344d1916
15:00:07.0 (68366779)|STATEMENT_EXECUTE|[178]
15:00:07.0 (68380256)|STATEMENT_EXECUTE|[179]
15:00:07.0 (68386333)|HEAP_ALLOCATE|[179]|Bytes:4
15:00:07.0 (68401241)|HEAP_ALLOCATE|[179]|Bytes:25
15:00:07.0 (68407362)|VARIABLE_SCOPE_BEGIN|[179]|sendingToBccAdd|List<String>|true|false
15:00:07.0 (68421543)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
15:00:07.0 (68429426)|VARIABLE_ASSIGNMENT|[179]|sendingToBccAdd|["MY EMAIL 1"]|0x2e1ff2aa
15:00:07.0 (68435010)|STATEMENT_EXECUTE|[180]
15:00:07.0 (68446165)|STATEMENT_EXECUTE|[181]
15:00:07.0 (68451784)|HEAP_ALLOCATE|[181]|Bytes:4
15:00:07.0 (68467537)|VARIABLE_SCOPE_BEGIN|[181]|sendingTocAdd|List<String>|true|false
15:00:07.0 (68480803)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
15:00:07.0 (68488466)|VARIABLE_ASSIGNMENT|[181]|sendingTocAdd|["MY EMAIL 1"]|0x5624acf0
15:00:07.0 (68493667)|STATEMENT_EXECUTE|[182]
15:00:07.0 (68511652)|STATEMENT_EXECUTE|[183]
15:00:07.0 (68515434)|HEAP_ALLOCATE|[183]|Bytes:28
15:00:07.0 (68534615)|STATEMENT_EXECUTE|[184]
15:00:07.0 (68537295)|HEAP_ALLOCATE|[184]|Bytes:72
15:00:07.0 (68549852)|STATEMENT_EXECUTE|[186]
15:00:07.0 (68551392)|STATEMENT_EXECUTE|[186]
15:00:07.0 (68552661)|STATEMENT_EXECUTE|[187]
15:00:07.0 (68554725)|HEAP_ALLOCATE|[187]|Bytes:36
15:00:07.0 (68571269)|USER_DEBUG|[187]|DEBUG|Yapa - Sending a non-template email.
15:00:07.0 (68578657)|STATEMENT_EXECUTE|[188]
15:00:07.0 (68599370)|HEAP_ALLOCATE|[188]|Bytes:4
15:00:07.0 (68652773)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
15:00:07.0 (68674221)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
15:00:07.0 (111182217)|EMAIL_QUEUE|[188]|subject: Single Email message Example, bccSender: false, saveAsActivity: true, useSignature: true, toAddresses: [MY EMAIL 1], ccAddresses: [MY EMAIL 1], bccAddresses: [MY EMAIL 2], plainTextBody: Hello!!!!!!!!!!This is a test email to test single email message program, 
15:00:07.0 (111271089)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
15:00:07.0 (111306604)|METHOD_EXIT|[63]|01p0U00000058Uf|sendEmailWithAttachment.sendEmailWithPDFAttachment(Id, String)
15:00:07.0 (111320211)|STATEMENT_EXECUTE|[65]
15:00:07.0 (111326767)|HEAP_ALLOCATE|[65]|Bytes:1
15:00:07.0 (111398051)|HEAP_ALLOCATE|[65]|Bytes:18
15:00:07.0 (111413617)|HEAP_ALLOCATE|[65]|Bytes:19


7)  I don't see any of them in my Junk email box for either email address.

8)  If I send an email directly from the UI for a Lead (i.e. not via code), it successfully reaches the email address.

Any ideas what's going wrong?
I would like to override the required field flag when creating a new Lead.  I would like to use the Standard New Lead page, so that Users can continue to modify the page layout(s) using standard Salesforce functionality.  I would like to continue to make this field required because there are a bunch of downstream processes, both technical and business, that will fail if the field is blank.

However, I can use Apex to determine the correct value for this field at time of record creation.  I can avoid User entry error if I can set it using Apex.  But required fields must be populated in order to Save a record, so right now the User still has to enter a value, even if it's junk.  Can I:

1.  Use Apex to set a required field value
2. Leave this as a required field (not just required on the page, but a field where Required = TRUE)
3. Not force the User to enter a value for this field at time of record creation (a Lead in this case)
4. Continue to use the Standard Lead creation page rather than a custom VF page.
I am trying to convert the contents of a Long Text Area into a String to include in an HTML Email.  The line of code I am using is:

emailHTML = emailHTML.replace('%%Opportunity.Dispatch_Notes__c%%', Opportunity.Dispatch_Notes__c);

emailHTML is the full HTML content of the email.  '%%Opportunity.Dispatch_Notes__c%%' is the tag in the HTML that I am trying to replace with the Opportunity's 'Dispatch_Notes__c' field.  That field's data type is Long Text Area.

When I try to save the Apex class in IDE, I get the error message on that line:

"Save error: Method does not exist or incorrect signature: [String].replace(String, Schema.SObjectField)"

I have any number of calls to .replace() on that 'emailHTML' string, so the method presumably isn't the problem, which means the signature is.  Apparently, it doesn't like replacing contents in a String ('emailHTML') with the contents of a Long Text Area field.

How do you include Long Text Area field content in HTML?  Is there some way to cast the Long Text Area type into a String type?
I have a customer who has very specific HTML that I need to use to format an email.  This HTML needs to be built in Apex and then passed to Visualforce.  (I need to query data in order to build the HTML content.)

They have provided a sample email with all the HTML that I need to generate.  I would like to copy-and-past this into my Apex variable.  However, because the HTML code is spread over multiple lines, I can't put it into a String because I get the error:

"line breaks not allowed in string literals"

This HTML is quite long, and removing the line breaks will not only make it almost impossible to analyse and troubleshoot, but I would have to go through each line of the HTML and remove its line breaks.

How can I add HTML to an Apex variable that displays across many lines in the Apex code, which can then be used to build an email?
I am trying to use Apex to send an email to a Contact pulling information from a Lead.  The Contact I am trying to send the email to is a field on the Lead, so I can get their ID using SOQL easily enough.  But the problem seems to be a fundamental and baffling incompatability between the combination of using email templates, sent to a Contact, using information from a Lead.  Here is what methods I have found so far:

1) Messaging.SingleEmailMessage:  This is the email class I am using.

2) setTemplateID:  easy enough using SOQL query

3) setToAddresses:  You can't use this if you are using an email template

4) setTargetObjectId(targetObjectId):  Generally, this is who will receive the email.  In this case, it would be a Contact.  Unfortunately, this also sets the context for the email for the merge fields.  For the merge fields, I need the context to be the LEAD.  So "targetObjectId" would need to be the LEAD Id, but the email must not be sent to the Lead.

5)  setTreatTargetObjectAsRecipient(treatAsRecipient) = FALSE:   This gets around the above problem.  This means that if I set the Lead as the TargetObjectID, then it's email is NOT the recipient.  *So I need to define the recipient some other way.  This is where it all falls apart.*

6)  setWhatId(ID):  WhatId is used to set the email's context.  The context is the LEAD.  So I can't set this to the Contact ID.  Further, you can't use a Lead with setWhatID!

7)  ALSO:  singleMail.setSaveAsActivity(false);  I'm not sure if I need to worry about this or not.

So, since I can't use setToAddresses, and I can't use either setTargetObjectId or setWhatId to set the recipient, what the heck do I use?  Do I really have to give up using a template?  I've seen something about Visualforce email templates, but I don't understand what it's talking about.

The error I am getting when I try to send:  "Invalid entity type for whatId."

BTW, I cannot use a workflow.  A workflow sets up the follow-up email as a pending Task.  You can't convert the Lead until all pending tasks are removed.  However, none of this is being handled manually.  It's all being handled via a third party integration that I have no control over.  So what is happening is that the integration is trying to convert the Lead and it fails because there is a pending email notification that had been created by the workflow.  So instead of a workflow I am trying to schedule a daily email notification for all Leads that were created prior to today that have not been acted upon.
 
Ok, this is weird.  I have a trigger that has been working happily for a few months now.  Today, I went to add some functionality to it in Sandbox, and am getting a 'List index out of bounds' error where (a) it previously worked in Sandbox, and (b) it currently works in Production.  I get this error when trying to create a new Lead.

I threw a bunch of system.debug statements around it to try and identify the problem, and blast it, I can see what line it goes wrong on, but don't know why!  Basically, I am getting a Lead ID from trigger.new and using it in a SOQL statement to retrieve the relevant fields.  This is an 'after insert' trigger where I am updating some fields.  I am successfully retrieving the list of Lead ID's from the trigger.new 'for' loop.  When I check for the size of this list outside of the for loop, it says it has a size of 1, which is correct.  I can show that ID in the debug log.

But then, when I make my SOQL query using this ID list, I get a return set of 0 size!

This makes no sense.  It has been working fine, and I can see that the list I get from trigger.new is NOT zero.  But for some reason the SOQL query doesn't return anything.

Here are the relevant codes of line and results:
-----------------------------------------------
ERROR RECEIVED:
Error: Invalid Data.
...execution of AfterInsert caused by: System.ListException: List index out of bounds: 0... (Points to the last line of code given below)

RELEVANT CODE:

List<Lead> submittedLeadList = new List<Lead>();
List<Id> theLeadID = new List<Id>();

system.debug('Entering the FOR loop to read trigger.new Lead');

for (Lead leadList : trigger.new) 
     {
        theLeadID.add(leadList.Id); 

        system.debug('Lead ID:  ' + leadList.Id);
        system.debug('Lead Name:  ' + leadList.FirstName + ' ' + leadList.LastName);
     }

system.debug('Exiting FOR loop');
system.debug('Lead ID after exiting loop:  ' + theLeadID[0]);
system.debug('Number of Leads retrieved from trigger.new:  ' + theLeadID.size());

submittedLeadList = [SELECT Id, FirstName, LastName, Company, Requested_Quote_Types__c, State, New_Lead__c FROM Lead WHERE Id IN : theLeadID LIMIT 1];

system.debug('Lead List Size:  ' + submittedLeadList.size());

system.debug('SOQL Query for submittedLeadList, for Lead:  ' + submittedLeadList[0].FirstName + ' ' + submittedLeadList[0].LastName);

DEBUG RESULTS:
USER_DEBUG|[32]|DEBUG|Entering the FOR loop to read trigger.new Lead
USER_DEBUG|[38]|DEBUG|Lead ID:  00Q63000003cPewEAE
USER_DEBUG|[39]|DEBUG|Lead Name:  Test Test1
USER_DEBUG|[42]|DEBUG|Exiting FOR loop
USER_DEBUG|[43]|DEBUG|Lead ID after exiting loop:  00Q63000003cPewEAE
USER_DEBUG|[44]|DEBUG|Number of Leads retrieved from trigger.new:  1
SOQL_EXECUTE_BEGIN|[46]|Aggregations:0|SELECT Id, FirstName, LastName, Company, Requested_Quote_Types__c, State, New_Lead__c FROM Lead WHERE Id IN :tmpVar1 LIMIT 1
SOQL_EXECUTE_END|[46]|Rows:0
USER_DEBUG|[47]|DEBUG|Lead List Size:  0
FATAL_ERROR|System.ListException: List index out of bounds: 0

This is an "after insert" trigger, so the record has to exist, and its ID has to be in trigger.new.  So how can I pass a valid ID to the SOQL statement and yet not get a result?  And how is it that this same code has worked in Sandbox before, and is currently working in Production?
I'm experiencing an unexpected error in my test class for an 'after insert' trigger.  First, the trigger works just fine in Sandbox.  So the issue has something to do with how I'm setting up my test class.  When I run the test on the test class in the Developer Console, I get the error:

-------------------------
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, leadsRoundRobin: execution of AfterInsert

caused by: System.ListException: List index out of bounds: 0

Trigger.leadsRoundRobin: line 34, column 1: []
-------------------------

If I look at the trigger leadsRoundRobin on line 34, I see that it's trying to assign the Trigger.New Lead to a variable inside the trigger:
(This is a simplified version of my trigger, including only the relevant bits)

-------------------------
trigger leadsRoundRobin on Lead (after insert) {

List<Id> triggerIds= new List<Id>();
Lead submittedLead = new Lead();

for (Lead triggerLead: trigger.new) 
        {
            triggerIds.add(triggerLead.Id);
        }

    // Get Submitted Lead Record
    submittedLeadList = [SELECT Id, FirstName, LastName, Company, Requested_Quote_Types__c, State, New_Lead__c FROM Lead WHERE Id IN : triggerIds];
    submittedLead = submittedLeadList[0];    <-- THIS IS LINE 34

etc....
-------------------------
Note that all this is doing, essentially, is assigning the Trigger.New Lead to 'submittedLead'.  It seems to me that the only way I could get the error 'List index out of bounds: 0' is if there IS no Trigger.New object!  That makes no sense.

Again, this is working perfectly fine running it in the Sandbox.  It's only trying to trigger it from the test class that gives this error.  The relevant bits of the Test class (I'm using 'SeeAllData=true' because my trigger references a Custom Setting):

-------------------------

@isTest(SeeAllData=true)
public class test_RoundRobin 
     { 
        // Add a Lead - Auto
            Lead testLead1 = new Lead();
                testLead1.Status = 'Open';
                testLead1.Company = 'Test Company 1';
                testLead1.LastName = 'Lead';
                testLead1.FirstName = 'Test1';
                if(contactRecordTypeMap.containsKey('Customer')) 
                    {
                        testLead1.RecordTypeId = leadRecordTypeMap.get('Customer').getRecordTypeId();
                    }
                testLead1.Phone = '1112223333';
                testLead1.Email = 'test@test.com';
                testLead1.Preferred_Contact_Method__c = 'Phone';
                testLead1.State = 'CA';
                testLead1.Requested_Quote_Types__c = 'Auto,';
                testLead1.New_Lead__c = FALSE;
            insert testLead1;   

            etc....
-------------------------

I can't figure it out.  It seems like the test class's 'insert testLead1' statement is firing the trigger, but not passing the Lead!

Any idea what I'm doing wrong?  I have a sneaky suspicion it has to do with 'SeeAllData=true', which I've never used before, but I just don't know.

Thanks!
I have the scenario where I am trying to convert a Lead but can't because there are pending time-based workflows.

The standard solution I come across is to create a custom checkbox field that, when it changes, causes the workflow criteria to no longer be true, and the pending workflow action quietly deletes itself.  It is then recommended that you either manually change this field value or override the conversion button to do this for you.

However, I have a complication that is preventing me from doing this.  The conversion is being triggered by a third party API call, not by a person.  So I need to have Apex change the value of this field.  And I can't get that to work.

I have tried a "before update" on the Lead, but that doesn't seem to do anything.  Investigation seems to indicate that the reason is that, before conversion, "isConverted" hasn't been set to TRUE, so I can't restrict my flag change to only conversions.

Paradoxically, I'm not sure I can use an "after update" either.  In that case, I am getting the error that I can't modify a converted Lead!  I know it is supposed to be possible to update converted Lead fields now, but I only have one User (I'm actually trying to do this in a Sandbox), and I can't modify my Profile with the necessary permission.  In any event, I'm not sure that would work either.  I think the workflow should fire after the apex code updates the field, but I'm not sure.  (And I can't test until I get the permissions sorted out.)

Surely someone has had to deal with this situation before?  To recap:

I have Leads that are getting converted by an API call.  The conversions are failing because there are pending time based workflows.  I need to use Apex to delete these time based workflows.  It must be Apex:  it cannot be done manually or via a Visualforce button.

How can this be done?

Thanks!
I am writing a trigger that merges a new Lead to an existing Lead if the new Lead's email matches the existing Lead's email.  The new Lead will be submitted by a web API.  The older (Master) Lead values will be maintained.  The new Lead values will only be added to the merged record if the Master Lead's field is blank.

I am having the problem that my database.merge statement is failing, apparently because it is trying to update ALL fields on the Lead during the merge, whether they can be updated or not.  For instance, here is the current error message I'm getting:

ERROR: Unable to create/update fields: IsDeleted, Name, Address, PhotoUrl, IsConverted, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, LastViewedDate, LastReferencedDate, LastTransferDate, Lead_Timeout_In_Seconds_Formula_OLD__c, Days_Since_Creation__c, Exceeds_Timeout_Limit__c, Default_Lead_Timeout_In_Seconds__c. Please check the security settings of this field and verify that it is read/write for your profile or permission set.

I' don't want to update fields like "IsConverted", "CreatedDate", "CreatedById", etc.  And some of those fields, like "PhotoUrl", don't even exist!

I don't understand why it's trying to update fields that I can't be updated.

Originally, I had SOQL queries used to retrieve the records I needed to check as duplicates, and so those queries only included a couple fields, and I got that error on those fields.  Going online, it seemed as if I needed to query for *all* fields.  Ok, bully, I found some code online that does this, in querying for all accessible fields and adding it to the Query strings.  And now I get the above error.

In short:  nowhere online have I seen that database.merge (or just a DML merge) tries to update fields during the merge and will error out if it encounters fields that haven't been directly queried or edited.  Likewise, I don't see where I'm trying to What lucky mistake am I making that is causing this problem?

I suspect that the part of the code beginning "for(String fieldName : mapFields.keySet())" is not limited to just the accessible fields, but (a) those fields should be populated in the master, so that loop shouldn't try to update them anyway, and (b) I still don't understand why the merge statement is trying to update fields that haven't been changed in the first place!

Here's the trigger.  Sorry if it's messy:  I've pulled a big chunk of it from the web in a desparate attempt to solve the problem.
--------------------------------------

trigger mergeLeads on Lead (after insert)
{
    // Merges a new Lead with an existing Lead based on matching email addresses.
    // Old Lead is the Master Lead - New Lead information will be added to the Master Lead only where the Master Lead information is blank
   
    // Set up variables
    List<Id> triggerId = new List<Id>();
    List<String> triggerEmail = new List<String>();
   
    // Read trigger into variable(s)
    for (Lead triggerLead : Trigger.new)
        {
            triggerId.add(triggerLead.Id);
            triggerEmail.add(triggerLead.Email);            
        }
 
    // Get all Lead fields formatted for use in a SOQL query
    Map<String, Schema.SObjectField> AllLeadFields = Schema.getGlobalDescribe().get('Lead').getDescribe().SObjectType.getDescribe().fields.getMap();
 
     List<String> accessiblefields = new List<String>();
 
      for(Schema.SObjectField field : AllLeadFields.values()){
            if(field.getDescribe().isAccessible())
                accessiblefields.add(field.getDescribe().getName());
        }
 
        String allfields='';
       
        for(String fieldname : accessiblefields)
            allfields += fieldname+',';
 
        allfields = allfields.subString(0,allfields.length()-1);
 
       // Query string to get all Leads with the same email address
        String masterSOQLQuery = 'SELECT ' + allfields + ' FROM Lead WHERE Email IN:  triggerEmail ORDER BY CreatedDate';
 
        // Query string to get all Leads with the same email address excluding the Master Lead
        String duplicatesSOQLQuery = 'SELECT ' + allfields + ' FROM Lead WHERE Email IN: triggerEmail AND Id != :masterLeadID LIMIT 2';
 
        List<Lead> matchingLeads = database.query(masterSOQLQuery);
 
    Lead masterLead = matchingLeads[0];
   
    Id masterLeadID = masterLead.Id;
   
    List<Lead> duplicateLeads = database.query(duplicatesSOQLQuery);
   
    // Go through the master and duplicate record fields, and update the master record where its fields are blank, but the duplicate's is populated
   
    SObjectType leadType = Schema.getGlobalDescribe().get('Lead');
    Map<String, Schema.sObjectField> mapFields = leadType.getDescribe().fields.getMap();
   
    for(String fieldName : mapFields.keySet())
        {
            if(masterLead.get(fieldName) == null && duplicateLeads[0].get(fieldName) != null)
                {
                    masterLead.put(fieldName, duplicateLeads[0].get(fieldName));
                }
        }
   
    // Merge the records
    Database.MergeResult[] results = Database.merge(masterLead, duplicateLeads, false);
  
}
 
We are implementing a third party scheduling app that the office staff use to create new work job appointments for specific Salesforce Users, which then gets fed back into Salesforce as a calendar Event, assigned to the appropriate User.

The Opportunity exists prior to the appointment scheduling.  Once the job has been assigned in the third party app and the calendar Event created in Salesforce, the ownership of the Salesforce Opp should be updated to match the User the Event has been assigned to.  The Event is connected to the Opportunity through the 'Related To' field.

I've seen lots of suggestions on how to do the reverse type of flow:  updating a task to match the parent object's ownership, but I'm going in the opposite direction:  Looking at the child (the Event Assigned To field) to update the related parent (the Opportunity Owner field)

I don't think this can be done with either a workflow or with process builder.  So I think I need to resort to Apex.  I don't consider myself an Apex specialist.  Is there a simple trigger that could accomplish this task?

Thanks!
I am trying to convert the contents of a Long Text Area into a String to include in an HTML Email.  The line of code I am using is:

emailHTML = emailHTML.replace('%%Opportunity.Dispatch_Notes__c%%', Opportunity.Dispatch_Notes__c);

emailHTML is the full HTML content of the email.  '%%Opportunity.Dispatch_Notes__c%%' is the tag in the HTML that I am trying to replace with the Opportunity's 'Dispatch_Notes__c' field.  That field's data type is Long Text Area.

When I try to save the Apex class in IDE, I get the error message on that line:

"Save error: Method does not exist or incorrect signature: [String].replace(String, Schema.SObjectField)"

I have any number of calls to .replace() on that 'emailHTML' string, so the method presumably isn't the problem, which means the signature is.  Apparently, it doesn't like replacing contents in a String ('emailHTML') with the contents of a Long Text Area field.

How do you include Long Text Area field content in HTML?  Is there some way to cast the Long Text Area type into a String type?
Ok, this is weird.  I have a trigger that has been working happily for a few months now.  Today, I went to add some functionality to it in Sandbox, and am getting a 'List index out of bounds' error where (a) it previously worked in Sandbox, and (b) it currently works in Production.  I get this error when trying to create a new Lead.

I threw a bunch of system.debug statements around it to try and identify the problem, and blast it, I can see what line it goes wrong on, but don't know why!  Basically, I am getting a Lead ID from trigger.new and using it in a SOQL statement to retrieve the relevant fields.  This is an 'after insert' trigger where I am updating some fields.  I am successfully retrieving the list of Lead ID's from the trigger.new 'for' loop.  When I check for the size of this list outside of the for loop, it says it has a size of 1, which is correct.  I can show that ID in the debug log.

But then, when I make my SOQL query using this ID list, I get a return set of 0 size!

This makes no sense.  It has been working fine, and I can see that the list I get from trigger.new is NOT zero.  But for some reason the SOQL query doesn't return anything.

Here are the relevant codes of line and results:
-----------------------------------------------
ERROR RECEIVED:
Error: Invalid Data.
...execution of AfterInsert caused by: System.ListException: List index out of bounds: 0... (Points to the last line of code given below)

RELEVANT CODE:

List<Lead> submittedLeadList = new List<Lead>();
List<Id> theLeadID = new List<Id>();

system.debug('Entering the FOR loop to read trigger.new Lead');

for (Lead leadList : trigger.new) 
     {
        theLeadID.add(leadList.Id); 

        system.debug('Lead ID:  ' + leadList.Id);
        system.debug('Lead Name:  ' + leadList.FirstName + ' ' + leadList.LastName);
     }

system.debug('Exiting FOR loop');
system.debug('Lead ID after exiting loop:  ' + theLeadID[0]);
system.debug('Number of Leads retrieved from trigger.new:  ' + theLeadID.size());

submittedLeadList = [SELECT Id, FirstName, LastName, Company, Requested_Quote_Types__c, State, New_Lead__c FROM Lead WHERE Id IN : theLeadID LIMIT 1];

system.debug('Lead List Size:  ' + submittedLeadList.size());

system.debug('SOQL Query for submittedLeadList, for Lead:  ' + submittedLeadList[0].FirstName + ' ' + submittedLeadList[0].LastName);

DEBUG RESULTS:
USER_DEBUG|[32]|DEBUG|Entering the FOR loop to read trigger.new Lead
USER_DEBUG|[38]|DEBUG|Lead ID:  00Q63000003cPewEAE
USER_DEBUG|[39]|DEBUG|Lead Name:  Test Test1
USER_DEBUG|[42]|DEBUG|Exiting FOR loop
USER_DEBUG|[43]|DEBUG|Lead ID after exiting loop:  00Q63000003cPewEAE
USER_DEBUG|[44]|DEBUG|Number of Leads retrieved from trigger.new:  1
SOQL_EXECUTE_BEGIN|[46]|Aggregations:0|SELECT Id, FirstName, LastName, Company, Requested_Quote_Types__c, State, New_Lead__c FROM Lead WHERE Id IN :tmpVar1 LIMIT 1
SOQL_EXECUTE_END|[46]|Rows:0
USER_DEBUG|[47]|DEBUG|Lead List Size:  0
FATAL_ERROR|System.ListException: List index out of bounds: 0

This is an "after insert" trigger, so the record has to exist, and its ID has to be in trigger.new.  So how can I pass a valid ID to the SOQL statement and yet not get a result?  And how is it that this same code has worked in Sandbox before, and is currently working in Production?
I'm experiencing an unexpected error in my test class for an 'after insert' trigger.  First, the trigger works just fine in Sandbox.  So the issue has something to do with how I'm setting up my test class.  When I run the test on the test class in the Developer Console, I get the error:

-------------------------
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, leadsRoundRobin: execution of AfterInsert

caused by: System.ListException: List index out of bounds: 0

Trigger.leadsRoundRobin: line 34, column 1: []
-------------------------

If I look at the trigger leadsRoundRobin on line 34, I see that it's trying to assign the Trigger.New Lead to a variable inside the trigger:
(This is a simplified version of my trigger, including only the relevant bits)

-------------------------
trigger leadsRoundRobin on Lead (after insert) {

List<Id> triggerIds= new List<Id>();
Lead submittedLead = new Lead();

for (Lead triggerLead: trigger.new) 
        {
            triggerIds.add(triggerLead.Id);
        }

    // Get Submitted Lead Record
    submittedLeadList = [SELECT Id, FirstName, LastName, Company, Requested_Quote_Types__c, State, New_Lead__c FROM Lead WHERE Id IN : triggerIds];
    submittedLead = submittedLeadList[0];    <-- THIS IS LINE 34

etc....
-------------------------
Note that all this is doing, essentially, is assigning the Trigger.New Lead to 'submittedLead'.  It seems to me that the only way I could get the error 'List index out of bounds: 0' is if there IS no Trigger.New object!  That makes no sense.

Again, this is working perfectly fine running it in the Sandbox.  It's only trying to trigger it from the test class that gives this error.  The relevant bits of the Test class (I'm using 'SeeAllData=true' because my trigger references a Custom Setting):

-------------------------

@isTest(SeeAllData=true)
public class test_RoundRobin 
     { 
        // Add a Lead - Auto
            Lead testLead1 = new Lead();
                testLead1.Status = 'Open';
                testLead1.Company = 'Test Company 1';
                testLead1.LastName = 'Lead';
                testLead1.FirstName = 'Test1';
                if(contactRecordTypeMap.containsKey('Customer')) 
                    {
                        testLead1.RecordTypeId = leadRecordTypeMap.get('Customer').getRecordTypeId();
                    }
                testLead1.Phone = '1112223333';
                testLead1.Email = 'test@test.com';
                testLead1.Preferred_Contact_Method__c = 'Phone';
                testLead1.State = 'CA';
                testLead1.Requested_Quote_Types__c = 'Auto,';
                testLead1.New_Lead__c = FALSE;
            insert testLead1;   

            etc....
-------------------------

I can't figure it out.  It seems like the test class's 'insert testLead1' statement is firing the trigger, but not passing the Lead!

Any idea what I'm doing wrong?  I have a sneaky suspicion it has to do with 'SeeAllData=true', which I've never used before, but I just don't know.

Thanks!
I have the scenario where I am trying to convert a Lead but can't because there are pending time-based workflows.

The standard solution I come across is to create a custom checkbox field that, when it changes, causes the workflow criteria to no longer be true, and the pending workflow action quietly deletes itself.  It is then recommended that you either manually change this field value or override the conversion button to do this for you.

However, I have a complication that is preventing me from doing this.  The conversion is being triggered by a third party API call, not by a person.  So I need to have Apex change the value of this field.  And I can't get that to work.

I have tried a "before update" on the Lead, but that doesn't seem to do anything.  Investigation seems to indicate that the reason is that, before conversion, "isConverted" hasn't been set to TRUE, so I can't restrict my flag change to only conversions.

Paradoxically, I'm not sure I can use an "after update" either.  In that case, I am getting the error that I can't modify a converted Lead!  I know it is supposed to be possible to update converted Lead fields now, but I only have one User (I'm actually trying to do this in a Sandbox), and I can't modify my Profile with the necessary permission.  In any event, I'm not sure that would work either.  I think the workflow should fire after the apex code updates the field, but I'm not sure.  (And I can't test until I get the permissions sorted out.)

Surely someone has had to deal with this situation before?  To recap:

I have Leads that are getting converted by an API call.  The conversions are failing because there are pending time based workflows.  I need to use Apex to delete these time based workflows.  It must be Apex:  it cannot be done manually or via a Visualforce button.

How can this be done?

Thanks!