2

I am new to Apex and would like to practice updating a custom email field which derives its value based on a custom lookup field. I understand this can be done with a simple formula, but want to practice creating triggers.

My example is, I have a custom object ‘Position__c’ with a lookup field ‘Hiring_Manager__c’ (lookup to User). I want to be able to populate ‘managers_email_address__c’ (custom email field) based on the ‘hiring_manager__c’ lookup field, which will pull the EMAIL address from the User record.

Here’s where I have gotten so far with error "Compile Error: Variable does not exist: hiring_manager__c at line 3 column 7":

Trigger updateEmail on Position__c (before insert, before update) {

    Map<Id, User> newMap = [SELECT ID, Email FROM User WHERE Id IN :hiring_manager__c];

for (Position__c p : Trigger.new){

User u = newMap.get(p.hiring_manager__c);

if (u != null) {

    p.managers_email_address__c = u.Email;

     }
  }            
}
0

You need to build an Id collection and query on that. You should investigate handler architecture and one trigger per object best practice. Regardless, change:

Map<Id, User> newMap = [SELECT ID, Email FROM User WHERE Id IN :hiring_manager__c];

to:

Set<Id> managerIds = new Set<Id>();
for (Position__c record : trigger.new)
    managerIds.add(record.Manager_Email__c);
Map<Id, User> managers = new Map<Id, User>([SELECT ID, Email FROM User WHERE Id IN :managerIds]);

I would also recommend working on concise field names and clear the value if the lookup is blank:

record.Manager_Email__c = !managers.containsKey(record.Hiring_Manager__c) ?
    null : managers.get(record.Hiring_Manager__c).Email;
  • Adrian & sfdcfox - Thank you so much. I really appreciate the help. I had to make a few tweeks to account for the correct API names in the proposed solution, but now it's working. – VMF Apr 14 '16 at 15:15
0

Here is the final trigger that is successfully updating the custom email field:

Trigger updateEmail on Position__c (before insert, before update) {

Set<Id> managerIds = new Set<Id>();
    for (Position__c record : trigger.new)
    managerIds.add(record.hiring_manager__c);
Map<Id, User> managers = new Map<Id, User>([SELECT ID, Email FROM User WHERE Id IN :managerIds]);

    for (Position__c p : Trigger.new){

User u = managers.get(p.hiring_manager__c);

if (u != null) {

    p.managers_email_address__c = u.Email;

        }
    }            
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.