+ Start a Discussion
Simon234Simon234 

"Break" doesn't work for "for"

I can't break this loop:

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;
             }
         }     
     }
I need to reassign an object if user's Role != 'X'.
mritzimritzi
Please make sure that there is only one User is returned.
[If there are more than one user in your org with same role, SOQL query will return multiple user records and loop will give inconsistent result]

You can also do away with inner loop if you only have one user in List.
List<User> userList = new List<User>([
	SELECT Id FROM User WHERE UserRole.Name = 'X' AND Name = 'some name' Limit 1
]);
//limit 1 ensures that there is only one user in the list
if(userList.size() > 0){
	for(Obj__c obj: Trigger.new){
		if(obj.OwnerId != userList[0].Id){
			obj.OwnerId = userList[0].Id;
            //this way all records in Trigger.new will be assigned to a particular user having said role.
            //break stops execution of the loop, and takes you out of the inner-most loop [should be used with caution]
		}
	}
}

Please mark this as Best Answer, if this helps solve your problem
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 
mritzimritzi
if your problem has been resolved, please mark correct answer as 'Best Answer', so that It will help others.