Skip to main content Build the future with Agentforce at TDX in San Francisco or on Salesforce+ on March 5–6. Register now.
plz help me with this.

1) I am having an User (let’s say Stephan). Who has a custom Field called : Immediate Manager. (Hierarchy Field)

2) We have an Account (let’s Say : Google). Whose owner is Stephan.

3) Whenever I will deactivate that user, then that User’s Immediate manager will become owner of all Account, which Stephan owned. Code with all best practices. (Bulkifying).

Also write Test method for this , which should cover at least 85%. functionality should be checked if working or not in test Class also.

trigger RecordOwnerChangeEx on User (after update) {   

 list<user> u=[select id, isActive, ManagerId from user where id in:trigger.new];

  // list<account> acc=[select id, ownerId from Account where ownerId in: ids ];

    list<account> ac=new list<account>();

    for(User uu:u){

        if(uu.IsActive == false && uu.ManagerId != null){

        for(account a:[select id, ownerId from Account where ownerId =:uu.id ]){

            a.ownerId = uu.ManagerId;

            ac.add(a);

        }

    }

    }

    update ac;

Tried with this but not working. 
11 answers
  1. Jul 22, 2016, 1:11 PM
    trigger RecordOwnerChangeEx on User (after update) { 

        list<account> lstAcc=new list<account>();

        List<ID> recordIds=new List<ID> ();

        for(Account acc : [select id, ownerid, owner.isActive, owner.ManagerId from account where ownerId IN: trigger.new]){

            if(acc.owner.isActive == false && acc.owner.ManagerId != null){

                acc.ownerid = acc.owner.ManagerId;

                lstAcc.add(acc);

                recordIds.add(acc.id);

            }

        }

      if(!lstAcc.isEmpty()){

       AccountHandler.updateAccounts(recordIds);}

    }

    public class AccountHandler {

      @future

      public static void updateAccounts(List<ID> recordIds) {

       List<Account> accts = [SELECT ownerid,owner.ManagerId FROM Account WHERE Id IN :recordIds];

       List<Account> accts1 =new List<Account>();

        for (Account acc:accts ){

        acc.ownerid = acc.owner.ManagerId;

        accts1.add(acc);

       }

        update accts1 ;

        }

    }
Loading
0/9000