0

I'm having trouble with a trigger that needs to update my custom email field on Asset with the email address from Contact that is a lookup field. The code I have is below and I can't figure out why it's not working:

trigger UpdateContactEmail on Asset (before insert, before update) {

 Set<Id> assetContactEmail = new Set<Id>();
 for(Asset record : trigger.new)
    assetContactEmail.add(record.ContactEmail__c);
 Map<Id, Contact> contactEmail = new Map<Id, Contact>([Select ID, Email 
                                             FROM Contact WHERE Id IN :AssetContactEmail]);

 for (Asset a : Trigger.new){

  Contact c = contactEmail.get(a.ContactEmail__c);

  if (c !=null) {
    a.ContactEmail__c = c.Email
  }
 }        
}
3
  • do you have other triggers on Asset that might be undoing the work of this one. Trigger order of execution is undefined – cropredy Aug 15 '16 at 23:24
  • 5
    Is ContactEmail__c a lookup field? That's an unfortunate field name for a lookup. – sfdcfox Aug 15 '16 at 23:28
  • I don't have any triggers that would undo the work. Contact Email is a text field which this trigger is supposed to populate. – SarahO Aug 16 '16 at 2:35
1

Please try this. Replace the line assetContactEmail.add(record.ContactEmail__c); with assetContactEmail.add(record.ContactId);

Thanks

1
  • Sorry, this didn't fix it. The record I need on my object (Asset) is the associated Contact Email Address and I update the Contact on the Asset via lookup field. So I need the trigger to fire when the contact is updated or when the asset record is created. – SarahO Aug 22 '16 at 18:26
0

There must be two custom fields on Asset, one will be lookup to Contact and other one to hold the value of the email field from Contact.
Currently, you are having only one lookup field and in your above code, you are trying to update same lookup field with email field which would not work.
Create, one more email field on Asset to hold the Contact Email, and make the below changes in your code Replace

a.ContactEmail__c = c.Email  

with

a.NewEmailFieldOnAsset__c = c.Email  

Also, you will need to write after update trigger on Contact as well, to copy the updated Email value on Contact to all its related Assets.

Note : You can create a simple formula field for Contact's email on Asset which will serve your purpose and there will be no need for trigger on both the objects (Asset and Contact). And your formula for new formula field should look something like this

ContactEmail__r.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.