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
DeekDeek 

Apex code not working as expected

Hi All,

 

Below is the trigger to update contact owner when account owner changes if the field is Unchecked otherwise no contact owner change.

 

 

jiah.choudharyjiah.choudhary

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.

 

 

DeekDeek

Hi Jiah,

 

I have removed 

if (c.OwnerId != oldOwnerId) in the Contact iteration and still doesnt work.

 

Please advise

jiah.choudharyjiah.choudhary

@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;
}

DeekDeek

HI Jiah,

 

Thanks for your quick response.

 

 

 

Please advise further.

 

Thx in Advance.

jiah.choudharyjiah.choudhary

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

DeekDeek

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.

 

 

 

 

jiah.choudharyjiah.choudhary

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