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
Jason Kuzmak 12Jason Kuzmak 12 

reference the EmailMessage RelatedToId in if statement

For some reason or another, I can't reference the RelatedToId field on the EmailMessage object. I'm trying to loop through and figure out if this value starts with "006" so I can determine if it's attached to an opportunity. I can see it on the list of fields in both workbench and Salesforce. I don't need to overwrite this information, but I do need to read it.
 

public with sharing class EmailMessageHandler {
	public static void handleAfterInsert() {
		System.debug('successfully handled after email message insert');
		List<String> fieldList = new List<String>();
		Map<Integer,String> fieldOrderMap = new Map<Integer,String>();
		Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.EmailMessage.fields.getMap();
		for(string fieldName: fieldMap.keySet()){
			if(fieldName == 'RelatedToId'){
				System.debug('Heyyyyy! We found RelatedToId!!');
			}
			else{
				System.debug('fieldname = '+fieldname);
			}
		}
        for(EmailMessage em : (List<EmailMessage>)trigger.new){
            if(em.RelatedToId == '12345'){
                
            }
        }
	}
}

The second for loop to the code above prevents it from saving, with the message 'Variable does not exist: RelatedToId', and the API name listed in Salesforce (RelatedTo) similarly does not work.

I remove this, save, and run the code. When I check the debug log, my goofy message never fires, and yet the field doesn't show up on the list of fields under that object either. Debug log says:

fieldname = id
fieldname = parentid
fieldname = activityid
fieldname = createdbyid
fieldname = createddate
fieldname = lastmodifieddate
fieldname = lastmodifiedbyid
fieldname = systemmodstamp
fieldname = textbody
fieldname = htmlbody
fieldname = headers
fieldname = subject
fieldname = fromname
fieldname = fromaddress
fieldname = toaddress
fieldname = ccaddress
fieldname = bccaddress
fieldname = incoming
fieldname = hasattachment
fieldname = status
fieldname = messagedate
fieldname = isdeleted
fieldname = replytoemailmessageid
fieldname = isexternallyvisible

Dataloader does download the info in this field, but I need apex access to this information. How do I accomplish this?