Thursday, 5 March 2015

Change of record owner after Approval Process

The problem

Change of record owner after Approval Process

I wanted to write a 2 step approval process.

One where you would send a record through for transfer, but would have to be accepted by the new person.

Salesforce is very good at 1 way approval process. (I.e., I send the record to you, but then you have send it somewhere else if you don't want it). However, in this instance it was important that the record was accepted before transfer.

This example needs an approval process set up where approval updates ChangeManagerApproved to true. We also need 2 owner fields - Escalation_Manager__c and New_Escalation_Manager__c.
// Comment
/*
* Reassigns Escalation Manager on Escalation after approval process is complete
* Output of approval process is ChangeManagerApproved = True
* If ChangeManagerApproved = True and yet the Escalation Manager and 
* New Escalation Manager fields then trigger should fire
* Only to fire on Update
*/
trigger reassignEscalationManager on Escalation__c (before update) {
    try {
        
        
        Set<Id> accountIds = new Set<Id>();
        Map<Id, Id> accountOwnerIdMap = new Map<Id, Id>();
        
        // all the accounts whose owner ids to look up
        for ( Escalation__c c : Trigger.new ) {
            
            if (c.ChangeManagerApproved__c == True && (c.Escalation_Manager__c <> c.New_Escalation_Manager__c)) {
                System.debug('Change of manager approved and new/old manager different - trigger firing');
                //Final action needs to be changing ChangeManagerApproved__c to False to prevent re-fire
                c.Escalation_Manager__c = c.New_Escalation_Manager__c;
                c.ChangeManagerApproved__c = False;
                c.New_Escalation_Manager__c = Null;
                    
            } //end if
            
        } //end for        
    } //end try
    catch(Exception e) 
    { //catch errors
        System.Debug('reassignEscalations failure: '+e.getMessage()); 
        //write error to the debug log
    }
    
} //end trigger