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
BrandonLBrandonL 

Apex Trigger to change ALL account contacts to a new account owner except for one person

Help please! I'm trying to setup a trigger for when an account owner changes that all contact owners change with the account owner EXCEPT for one individual (contact owner)..Can anyone help me add a line of code to say if the contact owner is 'Richard W' then don't change the contact owner, but if it's anyone else then change. My code so far is:

 

trigger reassignRelatedContactsAndOpportunities on Account (after update) {
   try {
      Set<Id> accountIds = new Set<Id>(); //set for holding the Ids of all Accounts that have been assigned to new Owners
      Map<Id, String> oldOwnerIds = new Map<Id, String>(); //map for holding the old account ownerId
      Map<Id, String> newOwnerIds = new Map<Id, String>(); //map for holding the new account ownerId
      Contact[] contactUpdates = new Contact[0]; //Contact sObject to hold OwnerId updates
      Opportunity[] opportunityUpdates = new Opportunity[0]; //Opportunity sObject to hold OwnerId updates
     
      for (Account a : Trigger.new) { //for all records
         if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) {
            oldOwnerIds.put(a.Id, Trigger.oldMap.get(a.Id).OwnerId); //put the old OwnerId value in a map
            newOwnerIds.put(a.Id, a.OwnerId); //put the new OwnerId value in a map
            accountIds.add(a.Id); //add the Account Id to the set
         }
      }
     
      if (!accountIds.isEmpty()) { //if the accountIds Set is not empty
         for (Account act : [SELECT Id, (SELECT Id, OwnerId FROM Contacts), (SELECT Id, OwnerId FROM Opportunities WHERE IsClosed = False) FROM Account WHERE Id in :accountIds]) { //SOQL to get Contacts and Opportunities for updated Accounts
            String newOwnerId = newOwnerIds.get(act.Id); //get the new OwnerId value for the account
            String oldOwnerId = oldOwnerIds.get(act.Id); //get the old OwnerId value for the account
            for (Contact c : act.Contacts) { //for all contacts
            if (c.Contact Owner == 'Richard W')
            if (c.OwnerId == c.OwnerId) { //if the contact is assigned to the old account Owner      
                  Contact updatedContact = new Contact(Id = c.Id, OwnerId = newOwnerId); //create a new Contact sObject
                  contactUpdates.add(updatedContact); //add the contact to our List of updates
               }
            }
            for (Opportunity o : act.Opportunities) { //for all opportunities
               if (o.OwnerId == oldOwnerId) { //if the opportunity is assigned to the old account Owner
                  Opportunity updatedOpportunity = new Opportunity(Id = o.Id, OwnerId = newOwnerId); //create a new Opportunity sObject
                  opportunityUpdates.add(updatedOpportunity); //add the opportunity to our List of updates
               }
            }
         }
         update contactUpdates; //update the Contacts
         update opportunityUpdates; //update the Opportunities
      }
   } catch(Exception e) { //catch errors
      System.Debug('reassignRelatedContactsAndOpportunities failure: '+e.getMessage()); //write error to the debug log
   }
}

J&A_DevJ&A_Dev

Hi,

 

You can check the value of the contact owner like so:

 

if (c.Owner.Name != 'Richard W') {
    // code to update the owner
}
BrandonLBrandonL

Got a little farther, thanks.. Can you help me with a line of code at "{ // code to update the owner }"  ?

 

When I change the account owner, none of the contact owners are changing now.

J&A_DevJ&A_Dev
for (Account act : [SELECT Id, (SELECT Id, OwnerId FROM Contacts), (SELECT Id, OwnerId FROM Opportunities WHERE IsClosed = False) FROM Account WHERE Id in :accountIds]) { //SOQL to get Contacts and Opportunities for updated Accounts
    for (Contact c : act.Contacts) { //for all contacts
        if (c.Contact.Owner.Name != 'Richard W') {
            c.OwnerId = newOwnerId.get(c.AccountId); // get the new ownerId of the account and assign to contact
            contactUpdates.add(c);
        }
    }
    for (Opportunity o : act.Opportunities) { //for all opportunities
        // check for owner name here also if needed
        o.OwnerId = newOwnerId.get(o.AccountId);
        opportunityUpdates.add(o);
    }
}
update contactUpdates; //update the Contacts
update opportunityUpdates; //update the Opportunities
BrandonLBrandonL

Getting the error "Error: Compile Error: Method does not exist or incorrect signature: newOwnerId.get(Id) at line 21 column 25"

 

Thanks a lot for your help

J&A_DevJ&A_Dev

I made a typo. Your map variable was named newOwnerIds, so replace all instances of newOwnerId with that and give it a try.

BrandonLBrandonL

I was able to enter the code without errors. But say the account owner is "Allison" and I change the account owner to "Joe", all the current contact owners owned by 'Allison' changes to Joe, but any contacts not owned by Allison doesn't change. I'm trying to figure out a way that all contact owners change to the new account owner Except for "Richard W". Every contact needs to change with the account owner except for Richard.. Current Code:

 

trigger reassignRelatedContactsAndOpport on Account (after update) {
   try {
      Set<Id> accountIds = new Set<Id>(); //set for holding the Ids of all Accounts that have been assigned to new Owners
      Map<Id, String> oldOwnerIds = new Map<Id, String>(); //map for holding the old account ownerId
      Map<Id, String> newOwnerIds = new Map<Id, String>(); //map for holding the new account ownerId
      Contact[] contactUpdates = new Contact[0]; //Contact sObject to hold OwnerId updates
      Opportunity[] opportunityUpdates = new Opportunity[0]; //Opportunity sObject to hold OwnerId updates
     
      for (Account a : Trigger.new) { //for all records
         if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) {
            oldOwnerIds.put(a.Id, Trigger.oldMap.get(a.Id).OwnerId); //put the old OwnerId value in a map
            newOwnerIds.put(a.Id, a.OwnerId); //put the new OwnerId value in a map
            accountIds.add(a.Id); //add the Account Id to the set
         }
      }
     
      if (!accountIds.isEmpty()) { //if the accountIds Set is not empty
         for (Account act : [SELECT Id, (SELECT Id, OwnerId FROM Contacts), (SELECT Id, OwnerId FROM Opportunities WHERE IsClosed = False) FROM Account WHERE Id in :accountIds]) { //SOQL to get Contacts and Opportunities for updated Accounts
            for (Contact c : act.Contacts) { //for all contacts
        if (c.Owner.Name != 'Richard W') {
            c.OwnerId = newOwnerIds.get(c.AccountId); // get the new ownerId of the account and assign to contact
            contactUpdates.add(c);
        }
    }
    for (Opportunity o : act.Opportunities) { //for all opportunities
        // check for owner name here also if needed
        o.OwnerId = newOwnerIds.get(o.AccountId);
        opportunityUpdates.add(o);
    }
}
        update contactUpdates; //update the Contacts
        update opportunityUpdates; //update the Opportunities         update contactUpdates; //update the Contacts
       
      }
   } catch(Exception e) { //catch errors
      System.Debug('reassignRelatedContactsAndOpportunities failure: '+e.getMessage()); //write error to the debug log
   }
}

BrandonLBrandonL

any other suggestions? Thanks