trigger Contactownertrigger on Account (after update) {
List<Contact> lstContactToBeUpdated = new List<Contact>(); Map<Id, Id> mapAccountId_OwnerId = new Map<Id, Id>();
for (Account a : Trigger.new) { if (!a.DNUC_Owner__c) { if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) { mapAccountId_OwnerId.put(a.Id, a.OwnerId); } } }
for(Contact objContact : [Select Id, OwnerId, AccountId from Contact where AccountId IN: mapAccountId_OwnerId.keySet()]) { objContact.OwnerId = mapAccountId_OwnerId.get(objContact.AccountId); lstContactToBeUpdated.add(objContact); }
I just noticed that, it is standard functionality to update child record's owner if parent record's owner changes. You can confirm that by deactivating your trigger. It updates the owner in contact even if you deactivate that trigger.
What you can do is, explicitely update the contact's owner with Account's old owner by using trigger.oldMap values along with check on other conditions. I tried this in my dev org and works perfectly. Try this. Hit kudos If it works for you.
Hi @dpat,
I would suggest you to remove the following line form your code :
if (c.OwnerId != oldOwnerId) in the Contact iteration.
Also, it would be more optimized if you used a map instead of 'for' inside a 'for' loop.
Hi Jiah,
I have removed
if (c.OwnerId != oldOwnerId) in the Contact iteration and still doesnt work.
Please advise
@dpat,
Try this:
trigger Contactownertrigger on Account (after update)
{
List<Contact> lstContactToBeUpdated = new List<Contact>();
Map<Id, Id> mapAccountId_OwnerId = new Map<Id, Id>();
for (Account a : Trigger.new)
{
if (!a.DNUC_Owner__c)
{
if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId)
{
mapAccountId_OwnerId.put(a.Id, a.OwnerId);
}
}
}
for(Contact objContact : [Select Id, OwnerId, AccountId from Contact where AccountId IN: mapAccountId_OwnerId.keySet()])
{
objContact.OwnerId = mapAccountId_OwnerId.get(objContact.AccountId);
lstContactToBeUpdated.add(objContact);
}
If(!lstContactToBeUpdated.isEmpty())
Update lstContactToBeUpdated;
}
HI Jiah,
Thanks for your quick response.
Please advise further.
Thx in Advance.
@dpat,
I just noticed that, it is standard functionality to update child record's owner if parent record's owner changes. You can confirm that by deactivating your trigger. It updates the owner in contact even if you deactivate that trigger.
H Jiah,
You are absolutely right Mate. Cheers!
I also noticed after your response that its a standard functionality. I think its being introduced in Winter 14 onwards.
@dpat,
What you can do is, explicitely update the contact's owner with Account's old owner by using trigger.oldMap values along with check on other conditions. I tried this in my dev org and works perfectly. Try this. Hit kudos If it works for you.