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
Scott MessnerScott Messner 

How to get the value of a non foreign key field in an Apex trigger

I'd like to create an Apex trigger to copy the values from two fields on a custom object to two fields on the Contact object. The custom object hed__Affiliation__c has a lookup to Contact. I'm doing this so we can pull these field into Pardot as our version of Pardot does not allow custom objects. I'm using Apex triggers instead of Process Builder because although Process Builder can copy the files, it cannot handle deleting, which will be my next step.

Here is my code. This works put it populates the account ID for educational institution instead of the name. I'm pulling from the organization field on hed__Affiliation__c which is a lookup to account. If I try to assign education institution to a.hed__Account__c.Name I receive a "A non foreign key field cannot be referenced in a path expression" error when trying to compile. How can I pull the name of the account instead of the ID?

Thanks!
 
trigger CopySchoolToContact on hed__Affiliation__c (after insert, after update) {
List<Contact> conList = new List<Contact>();
    
    for (hed__Affiliation__c a : [SELECT Id,hed__Contact__c,hed__Account__c,Educational_Institution_Class_Year__c FROM hed__Affiliation__c
                     WHERE Id IN :Trigger.New]) {
    
        conList.add(new Contact(Id=a.hed__Contact__c,
            					Educational_Institution__c=a.hed__Account__c, // This populates ID of account and not Name. 
                                Educational_Institution_Class_Year__c=a.Educational_Institution_Class_Year__c)); 
    }
    
    try{
        update conList;
    }
    catch(Exception E){
        system.debug('Error thrown is: ' + E.getMessage());
    }
}



 
Best Answer chosen by Scott Messner
Alain CabonAlain Cabon
The  problem is just a "r" (relationship) instead of a "c".

a.hed__Account__r.Name 

 

All Answers

Alain CabonAlain Cabon
The  problem is just a "r" (relationship) instead of a "c".

a.hed__Account__r.Name 

 
This was selected as the best answer
Scott MessnerScott Messner
Thank you Alain! That was it.
Sunil Shah 12Sunil Shah 12
Thank you Alain, I had a similar question regarding accessing the non foreign key value.