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
Tina DamTina Dam 

Trigger to Update Lookup Field Related to another Lookup Field


I have a custom object called Invoice_Header_Object that has a Master-Detail relationship with the Contact (a lookup field on the Contact object called Customer__c)

I also have another lookup field on the custom object that looks up the Account object (lookup field called Account__c)

I have a trigger that updates the Account__c field based on the Contact lookup field (grabs the Account on the Contact) and it works

My question is, how do I update the trigger to have it where if the Contact's Account is changed to another Account, have the trigger update the Account__c to reflect the new Account and also delete the associated Invoice Header from the previous Account

Here is my trigger:

trigger UpdateAccountIDInvoice on Invoice_Header__c (before insert,before update){
if (trigger.isBefore &&(trigger.isInsert||trigger.isUpdate))
set<Id> ContactIds = new set<ID>();
for(Invoice_Header__c cm:
Map<Id, Id> contactToAccountMap = new Map<Id, Id>();
for(contact c :[select Id, AccountId from contact where id in: contactIds])
for(Invoice_Header__c cm:
       cm.Account__c = contactToAccountMap.get(cm.customer__c);}   

thank you
Best Answer chosen by Tina Dam
You can write an after update trigger on Contact to do a dummy update on the Invoice Header that fires your trigger, this will re-calculate the lookups. 

trigger ContactTrigger on Contact(after update){

    Set<Id> contactIds = new Set<Id>();
    for(Contact c :{
        if(c.AccountId != Trigger.oldmap.get(c.Id).AccountId)

   List<Invoice_Header__c> updateHeaders = [select Id from Invoice_Header__c where Customer__c in :contactIds];

   if(updateHeaders != null) 
        update updateHeaders; // This will fire trigger and re-calculate the lookups