+ Start a Discussion
Simon234Simon234 

How to reassign an object to the user with Role 'X'?

We have a few users with Role 'X'. We need to reassign an object to one from these users, if it's created not by one of them. But my loop choose the last one and change owner even if owner is already correct (with Role 'X'). How can I fix it?
List<User> userList = [SELECT Id FROM User WHERE UserRole.Name = 'X'];

     for(Obj__c obj: Trigger.new){
         for(User user : userList){
             if(obj.CreatedById != user.Id){
                 obj.OwnerId = user.Id;
             }
         }     
     }

 
Sohan Raj GuptaSohan Raj Gupta
Hi Simon,

Use below code:
 
List<User> userList = [SELECT Id FROM User WHERE UserRole.Name = 'X'];
Boolean isOwner = false; 
 for(Obj__c obj: Trigger.new){
	 for(User user : userList){
		 if(obj.CreatedById != user.Id && !isOwner){
			 obj.OwnerId = user.Id;
			 isOwner = true;
		 }
	 }     
}

Hope this will help you. Let me know if it helped or you need any more assistance. 

Please mark this is as the solution if it solved your purpose.

Thanks,
Sohan Raj Gupta 
Raj VakatiRaj Vakati
Ttry this
 
List<User> userList = [SELECT Id FROM User WHERE UserRole.Name = 'X'];
Boolean isOwner = false; 
 for(Obj__c obj: Trigger.new){
	 If(! isOwner ){
		 
	 for(User user : userList){
		 if(obj.CreatedById != user.Id && !isOwner){
			 obj.OwnerId = user.Id;
			 isOwner = true;
		 }
	 }  
	 }
 isOwner = false;	 
}