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
wsmithwsmith 

Changing Owner to something else (when owner is being changed)" part 2

This post is based on the post "Changing Owner to something else (when owner is being changed)" http://community.salesforce.com/sforce/board/message?board.id=apex&thread.id=7847.  Thus also happens on Account objects.
There seems to be a workaround but I am not sure if this is a best practice or something may change, in a future Apex release, that breaks this.
The workaround is in the afterUpdate trigger:section
1) Query for the same sObject
2) Set the sObject field
3) Set a do not be a recursive trigger flag
4) Update the sObject

Pseudo code ..

1) Assume only one record at a time

2) Assume The user will use the Account UI to change the Account Owner

Code:
class TriggerHelper {
    public static Boolean ALLOWRECURSION = true;
}

trigger Accounts on Account (before update, after update) {

    if (!TriggerHelper.ALLOWRECURSION) {
        return;
    }

    if (
        (Trigger.isBefore) &&
        (Trigger.old[0].OwnerId != Trigger.new[0].OwnerId)
    ) {

        User u =
            [select MyFieldId__c from User where Id = :Trigger.new[0].OwnerId];
        Trigger.new[0].MyExecutive__c = u.MyFieldId__c;
        Trigger.new[0].OwnerId = u.MyFieldId__c;

    }

    if (
        (Trigger.isAfter) &&
        (Trigger.new[0].OwnerId != Trigger.new[0].MyExecutive__c) 
    ) {

       // Here we find that setting the Owner with the standard UI
       // retains the explicitly picked record Owner instead of what
       // was set in the isBefore section

       // Query for the record we are updating
       Account acct =
           [select OwnerId, Executive__c from Account where Id =
            Trigger.new[0].Id];

       // Set the field
       acct.OwnerId = acct.MyExecutive__c;

       TriggerHelper.ALLOWRECURSION = false;
       try {
           update acct;
       }
       finally {
           TriggerHelper.ALLOWRECURSION = true;
       }

    }

}

 Any thoughts?


Message Edited by wsmith on 09-11-2008 10:46 AM