• Kathryn Bullock
  • NEWBIE
  • 135 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 33
    Questions
  • 47
    Replies
Hello all,

I need to add flag images to a lead based on whether or not the conditions are met.  The conditions are as follows:

Red flag is assigned to any lead who has been contacted at least 6 over the last the 14 days, this is based off a field we have called '# of calls made', but we only want to register the last 14 days of changes for this field.

Green flag is assigned to any lead who has been contacted at least 4 times over the last 28 days, this is based off the same field as above.

Is this possible?  Any and all help is appreciated!
Hello All,

My Code is sending the email now, but it does not create a task or send the most recently attached file.  Please help!

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        list<Site_Survey__c> sitelist = [SELECT X3rd_Party_Installer__c, X3rd_Party_Installer__r.email FROM Site_Survey__c LIMIT 1];
		String toaddress= sitelist[0].X3rd_Party_Installer__r.email;
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] addr = new String[] {toaddress};
                mail.setToAddresses(addr);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
            insert newTask;
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page:
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController" action="{!sendSiteSurveyFunction}">
</apex:page>

 
I have a code that I am hoping will send an email to the X3_Party_Installer__r.Email and will create an activity on the record as well.   Unfortunately, there are no problems in the code, but I can't get it to work.  Please let me know if you have suggestions!!

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        list<Site_Survey__c> sitelist = [SELECT X3rd_Party_Installer__c, X3rd_Party_Installer__r.email FROM Site_Survey__c LIMIT 1];
		String toaddress= sitelist[0].X3rd_Party_Installer__r.email;
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] addr = new String[] {toaddress};
                mail.setToAddresses(addr);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page: 
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendSiteSurveyFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

 
I have no errors in the code, but the button is not working.  The idea is that it is supposed to send an email to the contact email of X3_Party_Installer and then create an activity as well.  Yet, when I press the button nothing happens.  Is there something wrong with the code?

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        list<Site_Survey__c> sitelist = [SELECT X3rd_Party_Installer__c, X3rd_Party_Installer__r.email FROM Site_Survey__c LIMIT 1];
		String toaddress= sitelist[0].X3rd_Party_Installer__r.email;
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] addr = new String[] {toaddress};
                mail.setToAddresses(addr);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page: 
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendSiteSurveyFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

 
I am trying to get the email to send to the contact in the lookup field x3_Party_Installer.  I have the following code, but I am getting an error 'Illegal Assignment from List to String' on Line 10.  Am I doing this wrong?  Or is there another way?

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        String toaddress = [SELECT X3rd_Party_Installer__c FROM Site_Survey__c LIMIT 1];
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {toaddress};
                mail.setToAddresses(toAddresses);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page: 
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendSiteSurveyFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

 
How do I change the following code to be on a custom object instead of Account?  And how do I have it send to the lookup account field on that object?
 
public class SendSiteSurveyEmailController {

    public String AccountId {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        AccountId = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        String toaddress = 'jamore@darlingii.com';
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {toaddress};
                mail.setToAddresses(toAddresses);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :AccountId Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/a2N?fcf=00B0h000009nbs5'+AccountId);
        reference.setRedirect(true);
        return reference;
    }
}

 
Hi,

Is it possible to create a button that will send an email and add one of the attached files, but only the most recently added file?  Please let me know if this is possible.
Hello,

I am receiving this error when I run a batch job on my accounts: The flow tried to update these records: null. This error occurred: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: DrivingDistanceTrigger: execution of AfterUpdate caused by: System.AsyncException: Future method cannot be called from a future or batch method: DrivingDistance1.calculateDistances(String) ()

I need this flow to work, but I don't know what is going wrong.  Please help!

Class:
public class DrivingDistance1 {
    
    public static boolean isExecuting = false;
    
    public static void execute(List<Account> triggerNew, list<Account> triggerOld){
        //filter unneeded objects
        //modify needed objects
        //save!
       	list<Account> filtered = filterAccounts(triggerNew, triggerOld);
        if(!System.isFuture()){
            for(Account f:filtered){
            	calculateDistances(f.id);
       		}
        }
    }
    
    private static List<Account> filterAccounts(List<Account> triggerNew, List<Account> triggerOld){
        List<Account> returnList = new List<Account>();
        for(Integer i = 0; i < triggerNew.size(); i++){
            if((triggerOld[i].UCO_service_provider__c != triggerNew[i].UCO_service_provider__c) || (triggerOld[i].shippingStreet != triggerNew[i].shippingStreet) ){
                returnList.add(triggerNew[i]);
            }
        }
        return returnList;
    }    
    
    @Future(callout=true)
    public static void calculateDistances(String AccountId){
		geopointe.API.DistanceService ds = new geopointe.API.DistanceService();
        // this will get the accounts where you already have the id.
        // ie: accounts that have changed.
        Account acc = [SELECT id, 
                                 distance1__c, 
                                 UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c, 
                                 UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c, 
                                 geopointe__Geocode__r.geopointe__Latitude__c, 
                                 geopointe__Geocode__r.geopointe__Longitude__c FROM Account WHERE Id = :AccountId LIMIT 1];
        
        ds.add(acc.geopointe__Geocode__r.geopointe__Latitude__c, acc.geopointe__Geocode__r.geopointe__Longitude__c,
                  acc.UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c,
                  acc.UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c); 
        
		List<double> distances = ds.getListOfDistances();
		acc.distance1__c = distances[0];		

        update acc;
    }
    
    
    public static void m1(List<Account> dAccount) {
        geopointe.API.DistanceService ds = new geopointe.API.DistanceService();
        // this will get the accounts where you already have the id.
        // ie: accounts that have changed.
        List<Account> accList = [SELECT id, 
                                 distance1__c, 
                                 UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c, 
                                 UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c, 
                                 geopointe__Geocode__r.geopointe__Latitude__c, 
                                 geopointe__Geocode__r.geopointe__Longitude__c FROM Account WHERE Id IN: dAccount];
        //create two lists.
        List<Account> origins = new List<Account>();
        List<Account> destinations = new List<Account>();
        
        // create list of origins and uco providers
        for(Account working:accList){
            ds.add(working.geopointe__Geocode__r.geopointe__Latitude__c, working.geopointe__Geocode__r.geopointe__Longitude__c,
                  working.UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c,
                  working.UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c);
        }
            
		//a list is ordered!
		List<double> distances = ds.getListOfDistances();
		
        for(Integer i = 0; i < accList.size(); i++){
            accList[i].distance1__c = distances[i];
        }

        update accList;
    }
}

Trigger:
trigger DrivingDistanceTrigger on Account (after update) {
    
    // because were running in an after update context
    // we have trigger.new, and trigger.old 
    //engage semaphor when the uco object or address has changed
    // disengage when it's not
	DrivingDistance1.execute(Trigger.New, Trigger.Old);
   
    
}

 
Hi,

I am trying to return the road miles with the Geopointe Distance Services.  Unfortunately, I believe my logic must be wrong.  The code is not working the way I was hoping.  What am I doing wrong?

Class:
public class DrivingDistance1 {
    public static void m1(List<geopointe__Geocode__c> lisofGeo) {
geopointe.API.DistanceService ds = new geopointe.API.DistanceService();
List<Account> accList = [SELECT id, 
                         distance1__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c, 
                         geopointe__Geocode__r.geopointe__Latitude__c, 
                         geopointe__Geocode__r.geopointe__Longitude__c FROM Account];
List<Account> origins = new List<Account>();
List<Account> destinations = new List<Account>();
    
    for(Integer i = 0; i < accList.size(); i++){
        if(Math.mod(i,2) == 0) {
            origins.add(accList.get(i));
        } else {
            destinations.add(accList.get(i));
        }
    }
    for(Integer i = 0; i < origins.size(); i++){
        ds.add((Double)origins.get(i).geopointe__Geocode__r.geopointe__Latitude__c,
              (Double)origins.get(i).geopointe__Geocode__r.geopointe__Longitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c);
    }
    for(Integer i = 0; i < origins.size(); i++){
        Double distance = ds.getDistanceAtIndex(i);
        origins.get(i).distance1__c = distance;
        destinations.get(i).distance1__c = distance;
    }
    update accList;
    }
}

Trigger:
trigger DrivingDistanceTrigger on Account (before insert) {
	DrivingDistance1.m1(Trigger.New);
}

Hi,

I am trying to write a trigger that will call the class whenever an update is made to the record.  I believe I am doing this wrong and I have many problems.  How do I write this trigger?

My class: 
public class DrivingDistance1 {
    public static void m1() {
geopointe.API.DistanceService ds = new geopointe.API.DistanceService();
List<Account> accList = [SELECT id, 
                         distance1__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c, 
                         geopointe__Geocode__r.geopointe__Latitude__c, 
                         geopointe__Geocode__r.geopointe__Longitude__c FROM Account LIMIT 1];
List<Account> origins = new List<Account>();
List<Account> destinations = new List<Account>();
    
    for(Integer i = 0; i < accList.size(); i++){
        if(Math.mod(i,2) == 0) {
            origins.add(accList.get(i));
        } else {
            destinations.add(accList.get(i));
        }
    }
    for(Integer i = 0; i < origins.size(); i++){
        ds.add((Double)origins.get(i).geopointe__Geocode__r.geopointe__Latitude__c,
              (Double)origins.get(i).geopointe__Geocode__r.geopointe__Longitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c);
    }
    for(Integer i = 0; i < origins.size(); i++){
        Double distance = ds.getDistanceAtIndex(i);
        origins.get(i).distance1__c = distance;
        destinations.get(i).distance1__c = distance;
    }
    update accList;
    }
}

My trigger:
trigger DrivingDistanceTrigger on Account (after update) {
  geopointe__Geocode__r.geopointe__Latitude__c[] = Trigger.new;
    DrivingDistance1.m1(distance);
}
Hi,

I am trying to write a class that will find the driving distance to a lookup on the account.  I am recieving this error:

Expecting '{' but was: 'for'

Here is the class:
public class DrivingDistance1 {
geopointe.API.DistanceService ds = new geopointe.API.DistanceService();
List<Account> accList = [SELECT id, 
                         distance__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c, 
                         geopointe__Geocode__r.geopointe__Latitude__c, 
                         geopointe__Geocode__r.geopointe__Longitude__c FROM Account LIMIT 1];
List<Account> origins = new List<Account>();
List<Account> destinations = new List<Account>();
    
    for(Integer i = 0; i < accList.size(); i++){
        if(Math.mod(i,2) == 0) {
            origins.add(accList.get(i));
        } else {
            destinations.add(accList.get(i));
        }
    }
    for(Integer i = 0; i < origins.size(); i++){
        ds.add((Double)origins.get(i).geopointe__Geocode__r.geopointe__Latitude__c,
              (Double)origins.get(i).geopointe__Geocode__r.geopointe__Longitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.geopointe__Geocode__r.geopointe__Latitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.geopointe__Geocode__r.geopointe__Longitude__c);
    }
    for(Integer i = 0; i < origins.size(); i++){
        Double distance = ds.getDistanceAtIndex(i);
        origins.get(i).distance__c = distance;
        destinations.get(i).distance__c = distance;
    }
    update accList;
}

 
Hi,

I am trying to save a code in Developer console and I am having trouble, but there is a problem.  Does this prevent me from saving?
When I write the code in the developer sandbox, it initially appears as though it is saving.  Yet, when I go to close the code I recieve the message: The tab "DrivingDistance1" has changes. Would you like to close without saving?

After I select 'Yes' because I know I have just saved I return to my code and it is all gone.  I have already attempted creating a new workspace.  What do I do?
I am trying to write a controller that will calculate the driving distance between the account and a lookup field on the account, called Facility__c.  Facility__c is attached to the Object Facility__c that needs to be referenced.  How do I fix my code?
 
public with sharing class CalculateDistanceMatrixGoogleMapsCtrl {
    public String accountId				{get;set;}
    public Account account1				{get;set;}
    public String account1Address		{get;set;}
    public String FacilityId			{get;set;}
    public String facility2				{get;set;}
    public String facility2Address		{get;set;}
    public CalculateDistanceMatrixGoogleMapsCtrl() {
        updateAccounts();
    }
    
    public List<Account> getAccounts() {
        return accounts;
    }
    
    public List<Facility__c> getFacilities() {
        return facilities;
    }
    
    public void updateAccounts() {
        
        if (!accounts.isEmpty()) {
            accounts.clear();
        }
        
        this.accounts = [SELECT ID, Name, ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, ShippingCountry FROM Account WHERE ShippingStreet <> '' LIMIT 1];
        
    }
    
    public void updateFacilities() {
        
        if (!facilities.isEmpty()) {
            facilities.clear();
        }
        
        this.facilities = [SELECT ID, Name, Street_Address__c FROM Facility__c WHERE Street_Address__c <> '' LIMIT 1];
        
    }
    
    public void updateAccountVariables() {
        
        for (Account a : accounts) {
            if (a.ID == accountId) {
                account1 = a;
            }
        }
        for (Facility__c f : facilities) {
            if (f.ID == facilityId) {
                facility2 = f;
            }
        }
    }
    
    public Boolean updateAccountAddresses() {
        
        if((
        		String.isBlank(account1.ShippingStreet)
        		&& String.isBlank(account1.ShippingCity)
        		&& String.isBlank(account1.ShippingState)
        		&& String.isBlank(account1.ShippingPostalCode)
        		&& String.isBlank(account1.ShippingCountry)
        ) && (
            String.isBlank(facility2.Street_Address__c))) {
                
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'Impossible build addresses for API call. Some fields are missing'));
                return false;
                
            }
        
        account1Address = EncodingUtil.urlEncode((
        	account1.ShippingStreet + ' ' +
        	account1.ShippingCity + ' ' +
        	account1.ShippingState + ' ' +
            account1.ShippingPostalCode + ' ' +
            account1.ShippingCountry).trim(),
            'UTF-8');
        
        facility2Address = EncodingUtil.urlEncode((
        	facility2.Street_Address__c).trim(),
            'UTF-8');
        
        System.debug('*** account1Address: ' + account1Address + ' , facility2Address: ' + facility2Address);
        return true;
    }
    
    public List<SelectOption> getAccountOptions() {
        
        List <SelectOption> options = new List <SelectOption>();
        options.add(new SelectOption('', '--None--'));
        for (Account a : accounts) {
            options.add(new SelectOption(a.Id, a.Name));
        }
        return options;
    }
    
    public void btnCalculateDistance() {
        
        if ((account1Id == null || account1Id =='') || (facility2Id == null || facility2ID =='')) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Select two Accounts then resubmit'));
            return;
            
        }
        
        updateAccountVariables();
        boolean response = updateAccountAddresses();
        if (response) {
            CalculateDistanceMatrixGoogleMaps gm = new CalculateDistanceMatrixGoogleMaps(account1Address, facility2Address);
            this.distance = isNull(gm.distance) ? 0.0 : gm.distance;
            this.duration = isNull(gm.duration) ? 'empty' : gm.duration;
            this.travelTime = isNull(gm.travelTime) ? 0 : gm.travelTime;
        } else {
            this.distance	=0.0;
            this.duration	='empty';
            this.travelTime	=0;
            
        }
    }
    
    public List <Account> accounts =new List <Accounts>();
    
    public Decimal distance		{get; set;}
    public String duration		{get; set;}
    public Integer travelTime	{get; set;}
    
    public Boolean isNull(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            if ((String)obj == '') {
                return true;
            }
        }
        if (obj instanceof Decimal) {
            if ((Decimal) obj == 0.0) {
                return true;
            }
        }
        if (obj instanceof Integer) {
            if ((Integer) obj == 0) {
                return true;
            }
        }
        return false;
    }
    
    public Boolean isDigit(Object obj) {
        Pattern p = Pattern.compile('^\\d+$');
        Matcher m = p.matcher((String)obj);
        if (m.find()) {
            return true;
        }
        return false;
    }
    
    public Boolean isText(Object obj) {
        Pattern p = Pattern.compile('^[a-zA-Z ]*$');
        Matcher m = p.matcher((String)obj);
        if(m.find()){
            return true;
        }
        return false;
    }
}

 
Hello,

I am trying to convert a javascript button to a lightning controller.  I have the basis of the controller, but how do I add the 'if this oppty type, then select this document' and the 'require these parts' sections in the lightning controller?

Javascript:
//********* Option Declarations (Do not modify )*********// 

var RC = '';var RSL='';var RSRO='';var RROS='';var CCRM='';var CCTM='';var CCNM='';var CRCL=''; var CRL='';var OCO='';var DST='';var LA='1';var CEM='';var CES='';var STB='';var SSB='';var SES='';var SEM='';var SRS='';var SCS ='';var RES=''; 

//********* Page Callout (Do not modify) *********// 
if("{!Opportunity.Authorized_Signer__c}" == false) 

alert('Must select an Authorized Signer to send to'); 


else{ 

//KIA 4-6-18 Must have Authorized Signer Email Address 
if("{!Opportunity.Authorized_Email__c}" == false) 

alert('Oops! You are trying to send to a contact with no email address. Go to the Contact Record, add an email address and then resend the DocuSign.'); 


else{ 

//KSJ 3-1-17 Must have agreement terms// 

if("{!Opportunity.Agreement_Term__c}" == ''|| "{!Opportunity.Agreement_Term__c}" == null ) 

alert('Agreement Term cannot be blank'); 

else{ 


//KSJ 3-1-17 Must have auto renewal terms// 

if("{!Opportunity.Auto_Renewal_Term__c}" == ''|| "{! Opportunity.Auto_Renewal_Term__c}" == null) 

alert('Auto Renewal Term must be filled in'); 

else{ 


//KSJ 3-1-17 Container type cannot be blank// 

if("{! Opportunity.Oppty_Type__c }" == "UCO Service" && {!(ISBLANK( Opportunity.Outdoor_Container_Type__c ))}) 

alert('Must have an Outdoor Container Type' ); 

else{ 


//KSJ 3-1-17 For Trap must have #of trap agreement// 

if("{! Opportunity.Oppty_Type__c }" == "Trap Service" && {!(ISBLANK( Opportunity.No_traps_agreement__c ))}) 

alert('# Traps - Agreement cannot be blank' ); 

else{ 

//KSJ 3-1-17 Indoor container cannot be blank// 

if("{! Opportunity.Oppty_Type__c }" == "UCO Service & Indoor Equipment" && "{! Opportunity.Indoor_Container_Type__c}" == '' || "{!Opportunity.Indoor_Container_Type__c}" == null ) 

alert('# Indoor Container Type cannot be Blank' ); 

else{ 


//KSJ 3-1-17 Must have a quote number// 

if("{! Opportunity.Oppty_Type__c }" == "UCO Service & Indoor Equipment" && {!(ISBLANK( Opportunity.Quote_No__c ))}) 

alert('Quote No cannot be blank' ); 

else{ 









//CES='TEST'; 
CES='Documents for your Review and Signature'; 
DST='{!Opportunity.Template_DST__c}'; 
//DST='XXXXXXXX'; 
//alert(DST); 

//4-17-17 RAM commented out Alert CRL 
// Custom Recipient List (Individual) 
CRL='Email~{!Opportunity.Authorized_Email__c};LastName~{!Opportunity.Authorized_Signer__c};Role~Authorized Signer;RoutingOrder~1,Email~{!Opportunity.OwnerEmail};FirstName~{!Opportunity.OwnerFirstName};LastName~{!Opportunity.OwnerLastName};Role~Opportunity Owner;RoutingOrder~2,Email~{!Opportunity.Office_Mgr_Email__c};LastName~{!URLENCODE(JSENCODE(Opportunity.Facility__c))};Role~Carbon Copy;RoutingOrder~3'; 
//alert(CRL); 


// Custom Contact Role Map (default config role) 
CCRM = 'Authorized Signer~Authorized Signer;Opportunity Owner~Opportunity Owner;Carbon Copy~Carbon Copy'; 

// Custom Contact Type Map (default Signer) 
CCTM = 'Authorized Signer~Signer;Opportunity Owner~Signer;Carbon Copy~Carbon Copy'; 

OCO='Send'; 


//********* Page Callout (Do not modify) *********// 

window.location.href = 
"/apex/dsfs__DocuSign_CreateEnvelope?DSEID=0&SourceID={!Opportunity.Id}&RC="+RC+"&RSL="+RSL+"&RSRO="+RSRO+"&RROS="+RROS+"&CCRM="+CCRM+"&CCTM="+CCTM+"&CRCL="+CRCL+"&CRL="+CRL+"&OCO="+OCO+"&DST="+DST+"&CCNM="+CCNM+"&LA="+LA+"&CEM="+CEM+"&CES= "+RES; 







}

Controller:
global class DocusignRedirect {
	private static final STRING PARAM_DSEID = 'DSEID';
    private static final STRING PARAM_SOURCE_ID = 'SourceID';
    private static final STRING PARAM_SOURCE_CRL = 'CRL';
    
    private Opportunity anOpportunity = null;
    
    public DocusignRedirect(ApexPages.StandardController stdController)
    {
        Id opportunityId = stdController.getRecord().Id;
        this.anOpportunity = DAL_Opportunity.getById(opportunityId);
    }
    
    public PageReference autoRun()
    {
        if (this.anOpportunity == null)
        {
            return null;
        }
        PageReference pageRef = Page.dsfs__Docusign_CreateEnvelope;
        pageRef.getParameters().put(PARAM_DSEID, '0');
        pageRef.getParameters().put(PARAM_SOURCE_ID, this.anOpportunity.Id);
        pageRef.getParameters().put(PARAM_CRL, this.getCRL());
        pageRef.setRedirect(true);
        return pageRef;
        
    }
    
    private String getCRL()
    {
        return 'Email~' + anOpportunity.Authorized_Email__c +
            ';Name~' + anOpportunity.Authorized_Signer__c +
            ';RoutingOrder~1;';
    }
}

 
Hi All,

I am trying to bring shipping information from XPO Logistics into Salesforce.  I was given a bearer token and I have to go through Postman to refresh the token every 12 hours.  Will I need to do an OAuth?  If so, will the callback URL be the Postman, the XPO Logistics or Salesforce?  I am very confused about what the callback URL does, and how I would get the callback URL if I need to get one on Postman.  Please help!
Hi All,
I am trying to update the info on a Visualforce page from the REST API from the site.  I was given a bearer token and I used Postman to get the access token.  I am confused because there are no errors, but the code isn't working.  How do I make this code work?
 
public class AccountShippingController {
   
    public String trackingnumber {get;set;}
    public String shipmentStatus {get;set;}
    public String shipperAddr {get;set;}
    public String consigneeAddr {get;set;}

    public AccountShippingController(ApexPages.StandardController stdController){
                    
        			Account account =(Account)stdController.getRecord();
                    account = [SELECT Id, XPO_Tracking__c FROM Account WHERE Id =:account.Id];
                    
                    String accountTracking = account.XPO_Tracking__c;
                    String apiKey = 'XXXXXXXX';
                    
                    String requestEndpoint = 'https://api.ltl.xpo.com/tracking/1.0/shipments/shipment-status-details';
                    requestEndpoint += '?referenceNumbers[]=' + accountTracking;
        			requestEndpoint += '&APPID=' + apiKey;
                    
                    Http http = new Http();
                    HttpRequest request = new HttpRequest();
                    request.setEndpoint(requestEndpoint);
                    request.setMethod('GET');
                    HttpResponse response = http.send(request);
                    
                    if (response.getStatusCode() == 200) {
                        
                        Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                        trackingnumber = String.valueOf(results.get('referenceNumbers'));
                        
                        Map<String, Object> shipmentStatusDtlsResults = (Map<String, Object>)(results.get('shipmentStatusDtls'));
                        shipmentStatus = String.valueOf(shipmentStatusDtlsResults.get('shipmentStatus'));
                        shipperAddr = String.valueOf(shipmentStatusDtlsResults.get('shipperAddr'));
                        consigneeAddr = String.valueOf(shipmentStatusDtlsResults.get('consigneeAddr'));
                    } else {
                        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'There was an error retrieving the information.  Double check the Tracking Number, then contact a system administrator.');
                        ApexPages.addMessage(myMsg);
                        
                    }
                }
            }
 
<apex:page standardController="Account" extensions="AccountShippingController" showHeader="false" sidebar="false">
           <apex:pageBlock title="Shipping Information">
    			<apex:pageBlockSection >
                
                    <apex:pageMessages />
               
                    <apex:outputText label="Shipping Status" value="{!shipmentStatus}"/>
                    <apex:outputText label="Shipper Information" value="{!shipperAddr}"/>
                    <apex:outputText label="Consignee Information" value="{!consigneeAddr}"/>
                                                                                                            
                </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

 
I am receiving this error message: Content cannot be displayed: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]

This is for a visualforce page.  Here is the Class:
public class AccountShippingController {
   
    public String trackingnumber {get;set;}
    public String shipmentStatus {get;set;}
    public String shipperAddr {get;set;}
    public String consigneeAddr {get;set;}

    public AccountShippingController(ApexPages.StandardController stdController){
        Account account =(Account)stdController.getRecord();
        account = [SELECT Id, XPO_Tracking__c FROM Account WHERE Id =:account.Id];
        
        String accountTracking = account.XPO_Tracking__c;
        String apiKey = 'XXXXXXXXXXXXXX';
        
        String requestEndpoint = 'https://app.ltl.xpo.com/appjs/tracking/#/tracking';
        requestEndpoint += 'details/' + accountTracking;
        requestEndpoint += '&APPID=' + apiKey;
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(requestEndpoint);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        
        if (response.getStatusCode() == 200) {
            
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            trackingnumber = String.valueOf(results.get('referenceNumbers'));
      		
            Map<String, Object> shipmentStatusDtlsResults = (Map<String, Object>)(results.get('shipmentStatusDtls'));
            shipmentStatus = String.valueOf(shipmentStatusDtlsResults.get('shipmentStatus'));
            shipperAddr = String.valueOf(shipmentStatusDtlsResults.get('shipperAddr'));
            consigneeAddr = String.valueOf(shipmentStatusDtlsResults.get('consigneeAddr'));
        } else {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'There was an error retrieving the information.  Double check the Tracking Number, then contact a system administrator.');
            ApexPages.addMessage(myMsg);
            
        }
    }
}
(I have removed the API key)

And the VF Page is:
<apex:page standardController="Account" extensions="AccountShippingController" showHeader="false" sidebar="false">
           <apex:pageBlock title ="Shipping Information">
    			<apex:pageBlockSection>
                
                    <apex:pageMessages/>
               
                    <apex:outputText label="Shipping Status" value="{!shipmentStatus}"/>
                    <apex:outputText label="Shipper Information" value="{!shipperAddr}"/>
                    <apex:outputText label="Consignee Information" value="{!consigneeAddr}"/>
                                                                                                            
                </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>
Any and all suggestions are welcome!  
 
Good day all,

I am trying to create a class and a trigger that will return the road miles between the Facility associated with the Account and the account.  Unfortunately, it is not working.  Any ideas on what I am doing wrong?

Class:
public class GeoCodeRoadMiles {
    public void RoadMiles(List<Account> Id) {
geopointe.API.DistanceService ds = new geopointe.API.DistanceService();
List<Account> accList = [SELECT id, distance__c, geopointe__Geocode__r.geopointe__Latitude__c, geopointe__Geocode__r.geopointe__Longitude__c FROM Account LIMIT 1];
List<Account> origins = [SELECT id, Facility__c  FROM Account];
List<Account> destinations = new List<Account>();

// Split up data into origins and destinations
    for(Integer i = 0; i < accList.size(); i++){
   if(Math.mod(i, 2) == 0){
       origins.add(accList.get(i));
   }else{
       destinations.add(accList.get(i));
   }
    }

// Add the latitude and longitudes for the origin destination pairs
for(Integer i = 0; i < origins.size(); i++){
    ds.add((Double)origins.get(i).geopointe__Geocode__r.geopointe__Latitude__c,
        (Double)origins.get(i).geopointe__Geocode__r.geopointe__Longitude__c,
        (Double)destinations.get(i).geopointe__Geocode__r.geopointe__Latitude__c,
        (Double)destinations.get(i).geopointe__Geocode__r.geopointe__Longitude__c);
}

// Get the distance results and update desired fields
for(Integer i = 0; i < origins.size(); i++){
    Double distance = ds.getDistanceAtIndex(i);
    String.valueof(origins.get(i).distance__c = distance);
    String.valueof(destinations.get(i).distance__c = distance);
}
update accList;
    }}

Trigger:
trigger RoadMiles on Account (after insert, after update, before insert, before update) {
    if(Trigger.isAfter){
        if(Trigger.isInsert){
        	GeoCodeRoadMiles RoadMiles = new GeoCodeRoadMiles();
        	RoadMiles.RoadMiles(Trigger.new);
    	}
    }
    if(System.IsBatch()  == false && System.isFuture()  == false){
        if(Trigger.isAfter){
            if(Trigger.isUpdate){
                GeoCodeRoadMiles RoadMiles = new GeoCodeRoadMiles();
                RoadMiles.RoadMiles(Trigger.new);
            }
        }
    }
}

I have a test class that uploaded to production with no problem.  Now I am unable to upload the trigger becuase of a problem on the test class???

Here is the error message:

System.StringException: Invalid id: Tacoma WA 
Stack Trace: Class.TestleadDuplicatePreventer.TestleadDuplicatePreventerwithOneOpp: line 39, column 1

But that is the test class.  Any and all help is appreciated!!

I have a code that I am hoping will send an email to the X3_Party_Installer__r.Email and will create an activity on the record as well.   Unfortunately, there are no problems in the code, but I can't get it to work.  Please let me know if you have suggestions!!

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        list<Site_Survey__c> sitelist = [SELECT X3rd_Party_Installer__c, X3rd_Party_Installer__r.email FROM Site_Survey__c LIMIT 1];
		String toaddress= sitelist[0].X3rd_Party_Installer__r.email;
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] addr = new String[] {toaddress};
                mail.setToAddresses(addr);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page: 
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendSiteSurveyFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

 
I have no errors in the code, but the button is not working.  The idea is that it is supposed to send an email to the contact email of X3_Party_Installer and then create an activity as well.  Yet, when I press the button nothing happens.  Is there something wrong with the code?

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        list<Site_Survey__c> sitelist = [SELECT X3rd_Party_Installer__c, X3rd_Party_Installer__r.email FROM Site_Survey__c LIMIT 1];
		String toaddress= sitelist[0].X3rd_Party_Installer__r.email;
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] addr = new String[] {toaddress};
                mail.setToAddresses(addr);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page: 
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendSiteSurveyFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

 
I am trying to get the email to send to the contact in the lookup field x3_Party_Installer.  I have the following code, but I am getting an error 'Illegal Assignment from List to String' on Line 10.  Am I doing this wrong?  Or is there another way?

Controller:
public class SendSiteSurveyEmailController {

    public String Site_Survey {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        Site_Survey = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        String toaddress = [SELECT X3rd_Party_Installer__c FROM Site_Survey__c LIMIT 1];
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {toaddress};
                mail.setToAddresses(toAddresses);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :Site_Survey Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            Contact ct = [SELECT id FROM Contact WHERE Email = :toaddress LIMIT 1];
            
            Task newTask = new Task(Description = 'Site Survey Email',
                                   Priority = 'Normal',
                                   Status = 'Completed',
                                   Subject = 'Site Survey',
                                   Type = 'Email',
                                   WhoId = ct.Id);
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/'+Site_Survey);
        reference.setRedirect(true);
        return reference;
    }
}

VF Page: 
<apex:page standardController="Site_Survey__c" extensions="SendSiteSurveyEmailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendSiteSurveyFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

 
How do I change the following code to be on a custom object instead of Account?  And how do I have it send to the lookup account field on that object?
 
public class SendSiteSurveyEmailController {

    public String AccountId {get;set;}
    
    Public SendSiteSurveyEmailController(ApexPages.StandardController controller) {
        AccountId = ApexPages.currentPage().getParameters().get('Id');
    }
    
    Public Pagereference SendSiteSurveyFunction() {
        String toaddress = 'jamore@darlingii.com';
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {toaddress};
                mail.setToAddresses(toAddresses);
            	mail.setReplyTo(toaddress);
            	mail.setSenderDisplayName('Name');
            	mail.setSubject('DarPro Site Survey');
            	mail.setBccSender(false);
            	mail.setUseSignature(true);
            	mail.setHtmlBody('<b> BODY </b>');
            
            List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [SELECT Name, Body, BodyLength FROM Attachment WHERE ParentId = :AccountId Order By LastModifiedDate DESC Limit 1]){
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
                //mail.setFileAttachments(new Messaging.SingleEmailMessage[] {efa});
            }
            mail.setFileAttachments(fileAttachments);
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        } catch(Exception e) {}
        
        PageReference reference = new PageReference('https://darlingingredients--griffsdbx.cs11.my.salesforce.com/a2N?fcf=00B0h000009nbs5'+AccountId);
        reference.setRedirect(true);
        return reference;
    }
}

 
Hi,

Is it possible to create a button that will send an email and add one of the attached files, but only the most recently added file?  Please let me know if this is possible.
Hi,

I am trying to return the road miles with the Geopointe Distance Services.  Unfortunately, I believe my logic must be wrong.  The code is not working the way I was hoping.  What am I doing wrong?

Class:
public class DrivingDistance1 {
    public static void m1(List<geopointe__Geocode__c> lisofGeo) {
geopointe.API.DistanceService ds = new geopointe.API.DistanceService();
List<Account> accList = [SELECT id, 
                         distance1__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c, 
                         UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c, 
                         geopointe__Geocode__r.geopointe__Latitude__c, 
                         geopointe__Geocode__r.geopointe__Longitude__c FROM Account];
List<Account> origins = new List<Account>();
List<Account> destinations = new List<Account>();
    
    for(Integer i = 0; i < accList.size(); i++){
        if(Math.mod(i,2) == 0) {
            origins.add(accList.get(i));
        } else {
            destinations.add(accList.get(i));
        }
    }
    for(Integer i = 0; i < origins.size(); i++){
        ds.add((Double)origins.get(i).geopointe__Geocode__r.geopointe__Latitude__c,
              (Double)origins.get(i).geopointe__Geocode__r.geopointe__Longitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Latitude__c,
              (Double)destinations.get(i).UCO_Service_Provider__r.Geopointe_Geocode__r.geopointe__Longitude__c);
    }
    for(Integer i = 0; i < origins.size(); i++){
        Double distance = ds.getDistanceAtIndex(i);
        origins.get(i).distance1__c = distance;
        destinations.get(i).distance1__c = distance;
    }
    update accList;
    }
}

Trigger:
trigger DrivingDistanceTrigger on Account (before insert) {
	DrivingDistance1.m1(Trigger.New);
}