Category Archives: triggers

Getting name of previous owner of account

1) Create a lookup field “Previous Owner” in Account as LookUp(User)

2) Create a trigger like this:

trigger OnAccountOwnerChanged on Account (before update) {
    for( Account a : Trigger.new ) {
        Account AcctBeforeUpdate = Trigger.oldMap.get( a.Id );

        if( AcctBeforeUpdate.OwnerId != a.OwnerId
                && ((String) a.OwnerId).startsWith( '005' ) )
            a.Previous_Owner__c = AcctBeforeUpdate.OwnerId;
    }
}

3) Use the “Previous Owner” in your reports and formulas. It will let you reference the user name since it is a lookup field (eg.: Previous_Owner__r.LastName + ‘, ‘ + Previous_Owner__r.FirstName).

4) The part that says

&& ((String) a.OwnerId).startsWith( '005' ) 

is for when the owner changes from one user to a queue. It will ignore queues as owners when setting the previous owner..

5) Create a test class like this:

public with sharing class TestTriggerOnAccountOwnerChanged {
    public static TestMethod void TestEverything() {
        // get default profile
        Profile objP = [ SELECT Id FROM Profile WHERE Name='Standard User' ]; 

        // create 2 users
        User objU1 = new User( Alias = 'TTOAOC1', Email='TTOAOC1@testorg.com' 
                        , CommunityNickName = 'TTOAOC1', EmailEncodingKey='UTF-8'
                        , UserName='TestingTTOAOC1@testorg.com', LastName = 'TTOAOC1'
                        , LocaleSidKey='en_US', ProfileId = objP.Id
                        , TimeZoneSidKey='America/Los_Angeles', LanguageLocaleKey='en_US' );
        insert objU1;
        User objU2 = new User( Alias = 'TTOAOC2', Email='TTOAOC2@testorg.com' 
                        , CommunityNickName = 'TTOAOC2', EmailEncodingKey='UTF-8'
                        , UserName='TestingTTOAOC2@testorg.com', LastName = 'TTOAOC2'
                        , LocaleSidKey='en_US', ProfileId = objP.Id
                        , TimeZoneSidKey='America/Los_Angeles', LanguageLocaleKey='en_US' );
        insert objU2;

        // create account
        Account AccountToTest;
        system.runAs( objU1 ) {
            AccountToTest = new Account( Name = 'TestingAccountOwnerChange' );
            insert AccountToTest;
        }

        // change owner of account
        system.runAs( objU2 ) {
            AccountToTest.OwnerId = objU2.Id;
            update AccountToTest;
        }

        // test the previous owner field
        AccountToTest = [ SELECT Id, Previous_Owner__C FROM Account WHERE Id = :AccountToTest.id ];
        system.assertEquals( objU1.Id, AccountToTest.Previous_Owner__c, 'Previous Owner Test : ' + AccountToTest.Previous_Owner__c );
    }
}
Advertisements