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
A.ZaykovA.Zaykov 

Apex Trigger to update Contact records, owned by inactive owners, does not work

Hi all,

The idea is: When a user has been deactivated, assign all of his/her contacts to the owner of the account they belong to.
Using the "isActive" field in the IF condition does not work. If I use different field, the code works.
public class InactiveUser {
    
    public static void deactivateUser(List<User> triggerNew, Map<Id, User> oldMap) {
        
    Set<Id> usersId = new Set<Id>();
    
    for(User us : triggerNew) {
        
        if(oldMap.get(us.Id).isActive != us.isActive && us.isActive == false) {
            usersId.add(us.Id);
        }
    }    
    //create a list of all contacts which belong to the inactive users
    List<Contact> contactsList = new List<Contact>();
    contactsList = [SELECT Id, OwnerId, Account.OwnerId FROM Contact WHERE OwnerId IN: usersId];
    
    List<Contact> contactsToBeUpdated = new List<Contact>();
    
    //loop through the Contact list and change the ownerId to the Account.OwnerId
    
    for(Contact c : contactsList) {
        c.OwnerId = c.Account.OwnerId;
        contactsToBeUpdated.add(c);
    }
    
    if(contactsToBeUpdated.size() > 0) {
            
            try {         
                update contactsToBeUpdated;
            } catch (System.DmlException ex) {
                System.debug(ex);
            }
        }  
    }     
}

Thanks,
Angel
VamsiVamsi
Hi,

Do contacts have Account owner information (Account.OwnerId ) ?