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

How do I reference the Contact in a lookup field?

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>

 
Best Answer chosen by Kathryn Bullock
Steven NsubugaSteven Nsubuga
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;
    }
}

 

All Answers

UjwalaUjwala
Hi,

please try below
from line 10....

string toaddress=new list<string>;
list<Site_Survey__c> sitelist = [SELECT X3rd_Party_Installer__c FROM Site_Survey__c LIMIT 1];
toaddress= sitelist[0].X3rd_Party_Installer__r.email   // please mention your email address field here
 
Kathryn BullockKathryn Bullock
Changing that now gives me a bunch of errors:
Unexpected token 'try'           Line 12
Expecting '}' but was 'catch'   Line 43
Unexpected token 'e'             Line 43
Unexpected token ')'              Line 43
Extra ')', at 'True'                    Line 46
Expecting '}' but was 'return'  Line 47

The new controller is: 
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 FROM Site_Survey__c LIMIT 1];
		toaddress= sitelist[0].X3rd_Party_Installer__r.email
        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;
    }
}

 
UjwalaUjwala
you have missed ; at end of line 11 
change name of string from toaddress to addr 
and what is email field name in X3rd_Party_Installer__c
Kathryn BullockKathryn Bullock
The email field name should just be Email. And that seems to have fixed most of the problems.  The only problem now is that it states:
Variable does not exist: toaddress in Lines 11, 14, 15, 16, and 35

New 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 FROM Site_Survey__c LIMIT 1];
		toaddress= sitelist[0].X3rd_Party_Installer__r.email;
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] addr = 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;
    }
}

 
Steven NsubugaSteven Nsubuga
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 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(toAddress);
            	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;
    }
}

 
UjwalaUjwala
if you have renamed toaddress to addr.. delete line 14, 16.. and replace  line mail.setToAddresses(toAddresses); with mail.setToAddresses(addr);
Kathryn BullockKathryn Bullock
@Steven Nsubuga When I try that I recieve the error: 'Method does not exist or incorrect signature: void setToAddresses(String) from the type Messaging.SingleEmailMessage' on Line 15
Steven NsubugaSteven Nsubuga
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 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;
    }
}

 
Kathryn BullockKathryn Bullock
@Ujwala I receive the same error when I try your method
Kathryn BullockKathryn Bullock
When I run the finished code I recieve this error on the record page:
SObject row was retrieved via SOQL without querying the requested field: Site_Survey__c.X3rd_Party_Installer__r
Error is in expression '{!sendSiteSurveyFunction}' in page sendsitesurveyemail: Class.SendSiteSurveyEmailController.SendSiteSurveyFunction: line 11, column 1
An unexpected error has occurred. Your development organization has been notified.
Steven NsubugaSteven Nsubuga
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;
    }
}

 
This was selected as the best answer
UjwalaUjwala
Please include X3rd_Party_Installer__r.email; field in query of sitelist
Irene QuesadaIrene Quesada
In the first available empty row, click a cell in the Field Name column, and then type a field name for (https://malletandplane.com/) the lookup field. Click in the Data Type column for that row, click the arrow and then, in the drop-down list, select Lookup Wizard.
Jean PerezJean Perez
Lookup fields allow you to create a chart that joins data from multiple collections in the same database. A lookup field brings in documents from a second collection whose values correspond to a field in your chart's main data source (https://celebritycontract.com/) .

Lookup fields are useful for leveraging parent/child and primary key/foreign key relationships between collections, or any situation in which a field in one collection references a field in another collection. Lookup fields use $lookup to retrieve matching documents from a remote collection.