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
Salesforce Admin 110Salesforce Admin 110 

populate random username to lookup(user) field

Hi I need help with apex .  I have created lookup field to user on contact object.  This is so i can bypass that fact that contacts are created by api user and have ownerid as api user.  in the absence of queues for contacts i have created the following trigger to populate allocated_user__c with a random user name thats is in anyone of 4 roleids:

List< User > uList = [select id from User where isActive = true && userroleid = ‘00E25000000QO8O’, ‘00E25000000QO8T’, 

‘00E25000000QO8d’, '00E25000000QO8i'];
 

if ( uList.size() > 0 )
{
  for ( contact con : Trigger.new )
  {
     if ( contact.allocated_owner__c == null ) contact.allocated_owner__c = uList.get( Math.floor( Math.random() * 

uList.size() ).intValue() );
  }
}

i get issues when adding to sandbox - 

could you be kind enough to correct this code?
Ashish DevAshish Dev
What is the error are getting?
Salesforce Admin 110Salesforce Admin 110
line3:83 no viable alternative at character ""
Ashish DevAshish Dev
this error generally occure when code is copy pasted from other place or there are double quotes instead of single.
Salesforce Admin 110Salesforce Admin 110
ok thanks for looking at this, i have copied this from notepad, now i have replaced the double quotes with single quotes and get following error:
expecting right square bracket, found ','

trigger popallocateduser on Contact (after insert) {

List<User> uList = [select id from User where isActive = true and userroleid = '00E25000000QO8O', '00E25000000QO8T', '00E25000000QO8d', '00E25000000QO8i' ];
 

if ( uList.size() > 0 )
{
  for ( contact con : Trigger.new )
  {
     if ( contact.allocated_owner__c == null ) contact.allocated_owner__c = uList.get( Math.floor( Math.random() * 

uList.size() ).intValue() );
  }
}  
Abhishek BansalAbhishek Bansal
Hi,

There were some mistakes in your code regarding the syntax which i have corrected.
Please use the below update code:
Set<String> roleIds = new Set<String>();
roleIds.add('00E25000000QO8O');
roleIds.add('00E25000000QO8T');
roleIds.add('00E25000000QO8d');
roleIds.add('00E25000000QO8i');

List<User> userList = new List<User>();
userList = [select id from User where isActive = true && UserRoleId IN :roleIds];

if(userList.size() > 0){
	for(Contact con : trigger.new){
		if(con.allocated_owner__c == null){
			con.allocated_owner__c = userList[0].id;//You can use your other methods like random to assign user accordingly
		}
	}
}
Let me know if you have any issue with the above code.

Thanks,
Abhishek
Salesforce Admin 110Salesforce Admin 110
thanks for this one last question is how do i write into trigger (sorry i am very new to apex):

uList.get( Math.floor( Math.random() * 

uList.size() ).intValue() );
Abhishek BansalAbhishek Bansal
I would advice you to not use Random method here because random can return any value and your list is containing only 4 elements so if this function returns any value than greater than 3 than you will get an error as List Index out of bound.

If you still want to use math.random than please make sure that it will return only values like 0,1,2,3 and i dont have any idea how to use it in Apex.

If you have got your required solution than please close this question by marking it as Solved.

Thanks,
Abhishek
Salesforce Admin 110Salesforce Admin 110
ok but this code doesn't populate the lookup(user) field with a username.......
Salesforce Admin 110Salesforce Admin 110
hi on this trigger i get error see below when i edit save contact record

trigger popallocateduser on Contact ( after update) {

    Set<String> roleIds = new Set<String>();
roleIds.add('00E25000000QO8O');
roleIds.add('00E25000000QO8T');
roleIds.add('00E25000000QO8d');
roleIds.add('00E25000000QO8i');
    
List<User> userList = new List<User>();
userList = [select id from User where isActive = true and UserRoleId IN :roleIds];

if(userList.size() > 0){
    for(Contact con : trigger.new){
        if(con.Allocated_User__c == null){
            con.Allocated_User__c = userList[0].id;
        }
    }
}
}

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger popallocateduser caused an unexpected exception, contact your administrator: popallocateduser: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.popallocateduser: line 15, column 1

i understand this is because i use after update??
Abhishek BansalAbhishek Bansal
Hi,

Please change your trigger from after update to before update because in after update your record will be only in read only mode and you cannot update it.

Thanks,
Abhishek
Ketankumar PatelKetankumar Patel
You can set upper limit to your random function.
  • You should replace after update with before update.
trigger popallocateduser on Contact (before update) {
​
Set<String> roleIds = new Set<String>();
roleIds.add('00E25000000QO8O');
roleIds.add('00E25000000QO8T');
roleIds.add('00E25000000QO8d');
roleIds.add('00E25000000QO8i');


List<User> userList = new List<User>();
userList = [select id from User where isActive = true and UserRoleId IN :roleIds];

if(userList.size() > 0){
    for(Contact con : trigger.new)
	{
     Integer Ran = (integer)(Math.random() * (userList.size()));
        if(con.Allocated_User__c == null)
		{
           con.Allocated_User__c = userList[Ran].id;
        }
    }
  }
}
Ketankumar PatelKetankumar Patel
Integer Ran = (integer)(Math.random() * (userList.size()));

You get rendom number from between 0 to userList.size().

I tried following 15 times in my execute anonymous apex window. 
 
Integer Ran = (integer)(Math.random() * 4);
System.debug(Ran);

This is what I got in user debug.

3
2
1
0
2
1
1
2
3
0
0
1
2
2
3