You need to sign in to do that
Don't have an account?

Trigger on Owner update not working
Hi, I've built a trigger that will update the Owner for the Account and its related contacts based on the User Lookup field in the Account. I was able to update the Owner of related contacts with an update in the Account.
If I change the Account in any of the Contact then the new Accounts owner should be added as Contacts Owner. I tried using the Trigger.OldMap. Can someone help me with what needs to be changed in my trigger...
If I change the Account in any of the Contact then the new Accounts owner should be added as Contacts Owner. I tried using the Trigger.OldMap. Can someone help me with what needs to be changed in my trigger...
trigger AccountOwnerUpdate on Account (before insert, before update) { Set<Id> accIds = new Set<Id>(); List<Contact> updatedConList = new List<Contact>(); Map<Id, String> newOwnerIds = new Map<Id, String>(); List<Contact> conList = [SELECT Id, AccountId FROM Contact WHERE AccountId IN: accIds]; for(Account acc : trigger.new) { accIds.add(acc.Id); newOwnerIds.put(acc.Id, acc.Coverage_Lead__c); if(acc.Coverage_Lead__c != NULL) { acc.OwnerId = acc.Coverage_Lead__c; } if(acc.Coverage_Lead__c == NULL){ acc.OwnerId = acc.LastModifiedById; } } if(trigger.isUpdate) { for(Account acc : trigger.new) { for(Contact con : conList) { if(con.AccountId!= NULL) { if(trigger.oldMap.get(con.Id).AccountId != con.AccountId) { accIds.add(con.AccountId); } } accIds.add(trigger.oldMap.get(con.Id).AccountId); } } } for(Account accs : [SELECT Id, LastModifiedById, (SELECT Id, Owner.Id, AccountId FROM Contacts) FROM Account WHERE Id IN:accIds]) { if(newOwnerIds.get(accs.Id) != NULL) { for(Contact con : accs.Contacts) { con.OwnerId = newOwnerIds.get(accs.Id); updatedConList.add(con); } } if(newOwnerIds.get(accs.Id) == NULL) { for(Contact con : accs.Contacts) { con.OwnerId = accs.LastModifiedById; updatedConList.add(con); } } } update updatedConList; }Thanks in Advance.
If you want to update the Account when a Contact record is updated, you need to create another Apex trigger on Contact. I would recommend you to use After update trigger context.