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
brianspatsobrianspatso 

Need to activate record Owner for update

The code I have written enables us to seperate Parent Companies from Departments, all within the Account object.

 

This particular code is intended to update all related records (Contacts, Opportunities and Sales Invoices) with the new Parent and Deparment details, when an Account is changed from Parent to Department.

 

The code so far is as follows:

trigger UpdateChildObjects on Account (after update) {

  Map<Id, Account> accountMap = new Map<Id,Account>();
  Account parent;
 
  for (Integer i = 0; i < Trigger.new.size(); i++){
    if (Trigger.new[i].Department__c == true && Trigger.old[i].Department__c == false) {
      accountMap.put( Trigger.new[i].Id, Trigger.new[i]);
    }
  }
  
  if( accountMap.size() > 0 ) {
  Set<Id> accountIds = accountMap.keySet();
  
  List<Contact> relatedContacts =
      [SELECT f.id, f.Accountid,  f.Owner.Name, f.Department__r.id, f.Ownerid
      FROM Contact f
      WHERE f.Accountid IN :accountIds
      FOR UPDATE];
      
  for ( Contact child : relatedContacts ) {
        if ( accountMap.containsKey( child.Accountid ) ) {
        parent = accountMap.get( child.Accountid );
        child.Department__c = child.Accountid;
        child.Accountid = parent.Parent_Company__c;
        }
      }
      

update relatedContacts;
   
}}

 Now so far, this code works fine. However, on child records where the owner is inactive it does not, obviously, work.

 

While this error is to be expected, I haven't managed to find a way to temporarily activate the owner so that I can update it.

 

Unfortunately, I cannot change the owner, as Deals need to stay with the same user.

 

I have tried something along the lines of:

  User getOwner = [SELECT Id, IsActive FROM User WHERE Id = :child.ID];

  getOwner.IsActive = True;

  update getOwner; 

 But it throws back a huge error, which I cannot decipher.

 

Funnily enough, if I swap:

  getOwner.IsActive = True;

 for:

  getOwner.Title = 'Test';

 it works fine!

 

Any advice?

 

****New Info****

 

This seems to be something to do with updating both the Contact object AND the User object - a Mixed DML Operation Error. I have done some research but the only solutions I can find are for test classes, not triggers. I think that's because it is not common to update a user from a trigger, but I cant be sure.

 

Here is an example of the problems other people have had - I just can't work out how to adapt it to my own code.