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
Nikhil Shrigod 17Nikhil Shrigod 17 

Changing the Owner of Account records by writing an apex trigger

trigger AccountTransfer on User (before insert)
{
  for(User u2:trigger.new)
  {
    List<Account> acc=[select name,owner.name  from account where owner.name = 'Mario Wade'];
    User u=[select Id from user where name='AB CD'];
    User u1=[select Id from user where name='Mario Wade'];
    
    if(u1.IsActive==false)
    {
        for(Account a:acc)
        {
             a.Owner=u;
            //a.OwnerId=u.id;
        }
    update acc;    
    }
  }
}

Say there are two users:
1)Mario Wade and
2)AB CD
And the owner of the records created of account object is Mario Wade.
Now what i want to do is, when the trigger gets fired, the owner of the account standard object records should get changed from Mario Wade to AB CD.

I have written above code for it, bur the owner of the records isn't getting changed.
So please help.
Abhishek BansalAbhishek Bansal
Hi Nikhil,

Please modify your trigger code as below:
trigger changeOwner on Account(before insert){
	Map<String,User> mapOfUser = new Map<String,User>();
	for(User usr : [Select Id, Name from User where Name IN ('AB CD','Mario Wade')]){
		mapOfUser.put(usr.Name,usr);
	}
	
	for(Account acc : trigger.new){
		if(acc.OwnerId == mapOfUser.get('Mario Wade').Id){
			acc.OwnerId = mapOfUser.get('AB CD').Id;
		}
	}
}

Please let me know if you need any other help/information on this.

Thanks,
Abhishek Bansal.