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
ShitalShital 

Lead Owner Assignment Apex code development

Hi All,

We are creating one lead at a time from operation custom object on some conditions met I want to do owner assignment in such way that if
1) existing operation BD Name is A then created lead from that operation record should goes to A,If BD name on operation record is B then lead goes to B and BD name on operation  is C then lead goes to C and 2) if BD name is other than A,B,C then lead goes to sequential among these three A,B,C .

For example, If BD Name on operation record is X then that lead goes to A,If BD name on operation is Y then Lead goes to B, BD name on operation is Z lead goes to C , BD Name on Operation is Q again lead goes to A and like wise

I have tried below code:
This code is working for First Scenario but for Second scenario it is Assigning first user in the list to every leads

global class SendMailtoLeadCreatedFromOperation{
    
    map<String,id> tempMap = new map<String,id>();
      
    global list<id> distributedInuserIDList = new list<id>();
   
    global SendMailtoLeadCreatedFromOperation(){
        tempMap = fetchOwnerForAssignment();
        system.Debug('---tempMap Map---'+ tempMap);
    }
    
    
    public void OwnerAssignment(list<Lead> ownerassignlist){
        
        system.debug('---ownerassignlist---'+ownerassignlist);
        
        list<User> distributedUsersList = [Select id,name from User where Website_Services__c = true];
         system.debug('---distributedUsersList---'+distributedUsersList+'---Size distributedUsersList---'+distributedUsersList.size());
        
        for(User temp : distributedUsersList){
            distributedInuserIDList.add(temp.id);
          }
         system.debug('---distributedInuserIDList---'+distributedInuserIDList);
          
          for(Lead scheduledoperation : ownerassignlist){
          
               if(tempMap.containskey(scheduledoperation.BDE_Name__c)){ 
                  
                  scheduledoperation.OwnerID = tempMap.get(scheduledoperation.BDE_Name__c);
                  scheduledoperation.User__c = tempMap.get(scheduledoperation.BDE_Name__c);
                     
                     
                }else{
                    
                    scheduledoperation.OwnerID = distributedInuserIDList.get(0);
                    scheduledoperation.User__c = distributedInuserIDList.get(0);
                     
                    system.debug('---ownerid is---'+scheduledoperation.OwnerID); 
                                     
                    distributedInuserIDList.add(scheduledoperation.User__c);
                    distributedInuserIDList.remove(0);
                    }
                    system.debug('---distributedInuserIDList contain---'+distributedInuserIDList+'---distributedInuserIDList SIZE---'+distributedInuserIDList.size());
            }   
    }
    
   
     public map<String,String> fetchOwnerForAssignment(){
    
        list<WebInternalLeadOwnerAssignmentCS__c> csList = [Select BDE_Name__c,UserId__c
                                                             from WebInternalLeadOwnerAssignmentCS__c
                                                             where isActive__c =: true];  
        system.debug('----csList---'+csList+'--csList size--'+csList.size()); 
        
        
            for(WebInternalLeadOwnerAssignmentCS__c temp : csList){
                if(tempMap.containskey(temp.BDE_Name__c))
                    tempMap.get(temp.BDE_Name__c);
                    else
                     tempMap.put(temp.BDE_Name__c,temp.UserId__c);
            }
            system.debug('----tempMap---'+tempMap+'--tempMap size--'+tempMap.size());
            return tempMap;
    }
    
 }



Can anyone help if possible
edanna kedanna k
Dear Shital G,

Please use Update DML at the end of for loop in your code as below!

for(Lead scheduledoperation : ownerassignlist){
          
               if(tempMap.containskey(scheduledoperation.BDE_Name__c)){ 
                  
                  scheduledoperation.OwnerID = tempMap.get(scheduledoperation.BDE_Name__c);
                  scheduledoperation.User__c = tempMap.get(scheduledoperation.BDE_Name__c);
                     
                     
                }else{
                    
                    scheduledoperation.OwnerID = distributedInuserIDList.get(0);
                    scheduledoperation.User__c = distributedInuserIDList.get(0);
                     
                    system.debug('---ownerid is---'+scheduledoperation.OwnerID); 
                                     
                    distributedInuserIDList.add(scheduledoperation.User__c);
                    distributedInuserIDList.remove(0);
                    }
                    system.debug('---distributedInuserIDList contain---'+distributedInuserIDList+'---distributedInuserIDList SIZE---'+distributedInuserIDList.size());
                    update scheduledoperation;
            }
-----------

Below is the sample code which was working fine!
public class LeadOwnerIsUser {
    
    public static void OwnerAssignment(List<Lead> lstLeads){
        
        // 2 users are present in my personal org with profile name starts with sys
        List<User> lstUser = [select id, name from User where Profile.name LIKE 'Sys%'];
        
        List<Id> lstUserId = new List<ID>();
        for(User u : lstUser){
            lstUserId.add(u.id);
        }        
        
        for(Lead oneLead : lstLeads){           
            
            oneLead.OwnerId = lstUserId[0];            
            oneLead.User__c = lstUserId[0];            
            lstUserId.add(oneLead.User__c);
            lstUserId.remove(0);
            
            update oneLead;
        }        
    }
}

call the above class with below code!
List<Lead> lstLds = [select id, name from Lead where Status = 'Open - Not Contacted'];
LeadOwnerIsUser.OwnerAssignment(lstLds);

 
ShitalShital
Hi edanna,

Above ownerassignlist list is coming from below custom object trigger on before update/insert event 


 if(trigger.isBefore
              && trigger.isUpdate || trigger.isBefore
              && trigger.isinsert){
             for(Operation__c opObj :trigger.new){
                
                if((trigger.oldMap.get(opObj.id).get('Website_Demo_Link__c') != trigger.newMap.get(opObj.id).get('Website_Demo_Link__c')) && 
                        trigger.newMap.get(opObj.id).get('Website_Demo_Link__c') != NULL
                        && opObj.Current_Status__c == 'File Sent'){
                    
                    Lead webServiceLead = new Lead();
                    webServiceLead.LastName = opObj.Contact_LastName__c;
                    webServiceLead.Company = opObj.New_Company_Name__c;
                    webServiceLead.Email = opObj.Contact_Email__c;
                    webServiceLead.BDE_Name__c = opObj.BDE_Name__c;
                    webServiceLead.Enquiry_For__c = 'Website Designing';
                    LeadList.add(webServiceLead);
                 }
             }
          }
        
        if(LeadList.size() > 0){
            insert LeadList;
         }

         

------Then lead trigger will invoke and wrote below code in Lead trigger


 public void bulkBefore()
    {
     if(trigger.isBefore 
            && trigger.isInsert){
            for(sObject weblead : trigger.new){
               Lead temp = (Lead)weblead;
                if(weblead.get('Enquiry_For__c') == 'Website Designing'){
                ownerassignlist.add(temp);
                }
                system.debug('--ownerassignlist--'+ownerassignlist);
              }
            
            if(ownerassignlist.size()>0){
                SendMailtoLeadCreatedFromOperation sm = new SendMailtoLeadCreatedFromOperation();
                sm.OwnerAssignment(ownerassignlist);
            }
        }
    }


so when I added "update scheduledoperation" am getting error as " DML statement cannot operate on trigger.new or trigger.old"

am I missing out something 
edanna kedanna k
Dear Shital,
Remove the below line and try!
update scheduledoperation
Reason for the above your error is  - your passing lead records from before trigger to class. so DML can not perform on the same object in before triggers.

Please let me know if it helps!

 
ShitalShital
Hi edanna,

Appreciate your help 

I tried above by removing "update scheduledoperation" statement then It is assigning only first user in the list everytime.It not assigning 2nd or 3rd user for one after another lead
edanna kedanna k
Dear Shital,
Can you please check the below.

1. distributedUsersList.size()? (Please list out the 3 names)
2. distributedInuserIDList.size()? 

For me Its working fine! Here is the similar pseudo code!
trigger LeadTrigger on Lead (before insert) {
    
    List<Lead> ownerassignlist = new List<Lead>();
	for(sObject weblead : trigger.new){
               Lead temp = (Lead)weblead;
                if(weblead.get('Status') == 'Open - Not Contacted'){
                ownerassignlist.add(temp);
                }
                system.debug('--ownerassignlist--'+ownerassignlist);
              }
            
            if(ownerassignlist.size()>0){
                LeadOwnerIsUser.OwnerAssignment(ownerassignlist);
                //SendMailtoLeadCreatedFromOperation sm = new SendMailtoLeadCreatedFromOperation();
                //sm.OwnerAssignment(ownerassignlist);
            }
}
public class LeadOwnerIsUser {
    
    public static void OwnerAssignment(List<Lead> lstLeads){
        
        // 2 users are present in my personal org with profile name starts with sys
        List<User> lstUser = [select id, name from User where Profile.name LIKE 'Sys%'];
        
        List<Id> lstUserId = new List<ID>();
        for(User u : lstUser){
            lstUserId.add(u.id);
        }        
        
        for(Lead oneLead : lstLeads){           
            
            oneLead.OwnerId = lstUserId[0];            
            oneLead.User__c = lstUserId[0];            
            lstUserId.add(oneLead.User__c);
            lstUserId.remove(0);           
           
        }        
    }
}

Am sure your code too work fine!
ShitalShital
Dear edanna,

1. distributedUsersList.size()? (Please list out the 3 names) ==> Sana,Pranak,Ronam
2. distributedInuserIDList.size()? ==> 3

In my org, Every time it is assigning Sana owner only to every lead (through trigger only 1 lead is coming at a time).
edanna kedanna k
Dear Shital,

Yes your are correct! every time your creating one lead through UI, so only first user will be assigned to each lead which you are going to create at a time.

Your are not inserting more than one lead records. So your are not testing for bulkifying lead records.

Please use workbench/dataloader to insert more lead records(lets say 6 records). Then you can see the result perfect!

Hope it helps!
ShitalShital

Hi edanna,

Thnaks for the explanation but my requirement is to create one lead from another record when some criteria met...so At the same time only one lead is coming not more than one.

so in this case how can we meet this requirement.

I would be very thankful to you for the same

edanna kedanna k
Dear Shital,

Here you go with changes in your class!
Added the lines of code which is in bold in below class.
global class SendMailtoLeadCreatedFromOperation{
    
    map<String,id> tempMap = new map<String,id>();
      
    global list<id> distributedInuserIDList = new list<id>();
	
	global list<User> distributedUsersList2Copy = new list<User>();
   
    global SendMailtoLeadCreatedFromOperation(){
        tempMap = fetchOwnerForAssignment();
        system.Debug('---tempMap Map---'+ tempMap);
    }
    
    
    public void OwnerAssignment(list<Lead> ownerassignlist){
        
        system.debug('---ownerassignlist---'+ownerassignlist);
        integer count = 0;
        list<User> distributedUsersList = [Select id,name from User where Website_Services__c = true];
//First time result - distributedUsersList.size()?  ==> Sana,Pranak,Ronam
//Second time result - distributedUsersList.size()? ==> Pranak,Ronam
//Third time result - distributedUsersList.size()? ==> Ronam
         system.debug('---distributedUsersList---'+distributedUsersList+'---Size distributedUsersList---'+distributedUsersList.size());
        
        for(User temp : distributedUsersList){
            distributedInuserIDList.add(temp.id);
          }
         system.debug('---distributedInuserIDList---'+distributedInuserIDList);
          
          for(Lead scheduledoperation : ownerassignlist){
          
               if(tempMap.containskey(scheduledoperation.BDE_Name__c)){ 
                  
                  scheduledoperation.OwnerID = tempMap.get(scheduledoperation.BDE_Name__c);
                  scheduledoperation.User__c = tempMap.get(scheduledoperation.BDE_Name__c);
                     
                     
                }else{
                    
                    scheduledoperation.OwnerID = distributedInuserIDList.get(0);
                    scheduledoperation.User__c = distributedInuserIDList.get(0);
                     
					distributedInuserIDList[0].Website_Services__c = false;					
					update distributedInuserIDList[0];
					
					count++;
					
					 if(count == 3)
					 {
						list<User> distributedUsersList2 = [Select id,name from User where Website_Services__c = false];
						for(User u: distributedUsersList2){
							u.Website_Services__c = true;
							distributedUsersList2Copy.add(u);
						}
						update distributedUsersList2Copy;
					 }
					 
					 
                    system.debug('---ownerid is---'+scheduledoperation.OwnerID); 
                                     
                    //distributedInuserIDList.add(scheduledoperation.User__c);
                    //distributedInuserIDList.remove(0);
                    }
                    system.debug('---distributedInuserIDList contain---'+distributedInuserIDList+'---distributedInuserIDList SIZE---'+distributedInuserIDList.size());
            }   
    }
    
   
     public map<String,String> fetchOwnerForAssignment(){
    
        list<WebInternalLeadOwnerAssignmentCS__c> csList = [Select BDE_Name__c,UserId__c
                                                             from WebInternalLeadOwnerAssignmentCS__c
                                                             where isActive__c =: true];  
        system.debug('----csList---'+csList+'--csList size--'+csList.size()); 
        
        
            for(WebInternalLeadOwnerAssignmentCS__c temp : csList){
                if(tempMap.containskey(temp.BDE_Name__c))
                    tempMap.get(temp.BDE_Name__c);
                    else
                     tempMap.put(temp.BDE_Name__c,temp.UserId__c);
            }
            system.debug('----tempMap---'+tempMap+'--tempMap size--'+tempMap.size());
            return tempMap;
    }
    
 }
Hope it helps!
ShitalShital

Dear edanna,

Thank you very much for kind support..Have excecuted this code which is working finely for 3 leads only but if 4th lead is inserting  throwing exception 'list out of bound' as we are updating Website_Services__c checkbox false so distributedUsersList list is getting empty while query on user object ( distributedUsersList.size() ==>> 0 )

Because Count++ is not incresing the vaule I checked in debug every time got count = 1 only its not increasing so automatically if (count == 3) is got skip so webservice__c checkbox remains false . M not able to understand why count++ is not incresing the value

so list<User> distributedUsersList = [Select id,name from User where Website_Services__c =true];

result ==>> distributedUsersList.size is 0

Threfore lead is not getting inserted and thwng excption as list out of bound.

 

Appreciate your efforts I am trying my best to acheive this 

edanna kedanna k
Dear Shital,
Perfect!
Please declare count as static as below!
public static integer count = 0;
Try it and let me know!
 
ShitalShital

Dear edanna,

Please review the code..its not getting increased..please let me know am I doing any mistke  

public class SendMailtoLeadCreatedFromOperation{
    
    map<String,id> tempMap = new map<String,id>();
      
    public static integer count = 0;   // added here
        
    public list<id> distributedInuserIDList = new list<id>();
   
    public list<User> distributedUsersList2Copy = new list<User>();
    
    public SendMailtoLeadCreatedFromOperation(){
        
        tempMap = fetchOwnerForAssignment();
     
    }
   
    
   public void OwnerAssignment(list<Lead> ownerassignlist){

        system.debug('---ownerassignlist---'+ownerassignlist);

       list<User> distributedUsersList = [Select id,name from User where Website_Services__c = true];

    /* First time result - distributedUsersList.size()?  ==> Sana,Pranak,Ronam

   Second time result - distributedUsersList.size()? ==> Pranak,Ronam

    Third time result - distributedUsersList.size()? ==> Ronam */
    

         system.debug('---distributedUsersList---'+distributedUsersList+'---Size distributedUsersList---'+distributedUsersList.size());

         for(User temp : distributedUsersList){

            distributedInuserIDList.add(temp.id);

          }

         system.debug('---distributedInuserIDList---'+distributedInuserIDList);

          for(Lead scheduledoperation : ownerassignlist){

           if(tempMap.containskey(scheduledoperation.BDE_Name__c)){

                  scheduledoperation.OwnerID = tempMap.get(scheduledoperation.BDE_Name__c);

                  scheduledoperation.User__c = tempMap.get(scheduledoperation.BDE_Name__c);

                 }else{

                    scheduledoperation.OwnerID = distributedInuserIDList.get(0);

                    scheduledoperation.User__c = distributedInuserIDList.get(0);

                     distributedUsersList[0].Website_Services__c = false;                 

                    update distributedUsersList[0];

                     
                    count++;        // This is not getting increased
                    
                    system.debug('--count is--'+count);

                     if(count == 3)

                     {
                     system.debug('--in here to update CB--');
                  list<User> distributedUsersList2 = [Select id,name from User where Website_Services__c = false];

                        for(User u: distributedUsersList2){

                            u.Website_Services__c = true;

                            distributedUsersList2Copy.add(u);

                        }

                        update distributedUsersList2Copy;

                     }

                        
                    }

                    system.debug('---distributedInuserIDList contain---'+distributedInuserIDList+'---distributedInuserIDList SIZE---'+distributedInuserIDList.size());

            }  

    }   
   
    
    public map<String,String> fetchOwnerForAssignment(){
    
           list<WebInternalLeadOwnerAssignmentCS__c> csList = [Select BDE_Name__c,UserId__c
                                                             from WebInternalLeadOwnerAssignmentCS__c 
                                                             where isActive__c =: true];  
                
            system.debug('----csList---'+csList+'--csList size--'+csList.size()); 
        
        
            for(WebInternalLeadOwnerAssignmentCS__c temp : csList){
                if(tempMap.containskey(temp.BDE_Name__c))
                    tempMap.get(temp.BDE_Name__c);
                    else
                     tempMap.put(temp.BDE_Name__c,temp.UserId__c);
                }
          system.debug('----tempMap---'+tempMap+'--tempMap size--'+tempMap.size());
            return tempMap;
    }
    
  }



Thank You !!!!!!

edanna kedanna k
Dear Shital,
Please try below!
public class SendMailtoLeadCreatedFromOperation{
    
    map<String,id> tempMap = new map<String,id>();
      
    public static integer count = 0;   // added here
        
    public list<id> distributedInuserIDList = new list<id>();
   
    public list<User> distributedUsersList2Copy = new list<User>();
    
    public SendMailtoLeadCreatedFromOperation(){
        
        tempMap = fetchOwnerForAssignment();
     
    }
   
    
   public void OwnerAssignment(list<Lead> ownerassignlist){

        system.debug('---ownerassignlist---'+ownerassignlist);

       list<User> distributedUsersList = [Select id,name from User where Website_Services__c = true];

    /* First time result - distributedUsersList.size()?  ==> Sana,Pranak,Ronam

   Second time result - distributedUsersList.size()? ==> Pranak,Ronam

    Third time result - distributedUsersList.size()? ==> Ronam */
    

         system.debug('---distributedUsersList---'+distributedUsersList+'---Size distributedUsersList---'+distributedUsersList.size());

         for(User temp : distributedUsersList){

            distributedInuserIDList.add(temp.id);

          }

         system.debug('---distributedInuserIDList---'+distributedInuserIDList);

          for(Lead scheduledoperation : ownerassignlist){

           if(tempMap.containskey(scheduledoperation.BDE_Name__c)){

                  scheduledoperation.OwnerID = tempMap.get(scheduledoperation.BDE_Name__c);

                  scheduledoperation.User__c = tempMap.get(scheduledoperation.BDE_Name__c);

                 }else{

                    scheduledoperation.OwnerID = distributedInuserIDList.get(0);

                    scheduledoperation.User__c = distributedInuserIDList.get(0);
                     

                    if(distributedInuserIDList.get(0) != NULL){ 
                     count++;        // This is not getting increased
                    
                     system.debug('--count is--'+count);

                     if(count == 3)

                     {
                     system.debug('--in here to update CB--');
                  list<User> distributedUsersList2 = [Select id,name from User where Website_Services__c = false];

                        for(User u: distributedUsersList2){

                            u.Website_Services__c = true;

                            distributedUsersList2Copy.add(u);

                        }

                        update distributedUsersList2Copy;

                     }
					}
					distributedUsersList[0].Website_Services__c = false;                 

                    update distributedUsersList[0];

                        
                    }

                    system.debug('---distributedInuserIDList contain---'+distributedInuserIDList+'---distributedInuserIDList SIZE---'+distributedInuserIDList.size());

            }  

    }   
   
    
    public map<String,String> fetchOwnerForAssignment(){
    
           list<WebInternalLeadOwnerAssignmentCS__c> csList = [Select BDE_Name__c,UserId__c
                                                             from WebInternalLeadOwnerAssignmentCS__c 
                                                             where isActive__c =: true];  
                
            system.debug('----csList---'+csList+'--csList size--'+csList.size()); 
        
        
            for(WebInternalLeadOwnerAssignmentCS__c temp : csList){
                if(tempMap.containskey(temp.BDE_Name__c))
                    tempMap.get(temp.BDE_Name__c);
                    else
                     tempMap.put(temp.BDE_Name__c,temp.UserId__c);
                }
          system.debug('----tempMap---'+tempMap+'--tempMap size--'+tempMap.size());
            return tempMap;
    }
    
  }

haaaaaaaa.....Let me know!
edanna kedanna k
Dear Shital,

Please let me know if it helps!
 
ShitalShital

Hi edanna,

Thank you very much for your help.

Actually above code is not working out getting the same issue as

If 1st lead is coming assigning owner sana 

2nd lead is coming assigning owner Pranak

3rd lead is coming assigning owner Ronam which is good but when

4th lead is coming there is no owner assignmnt done getting exception as list index out of bound why bcz above distributedUsersList is getting empty 


@ I am learning apex if u have suitable material fr the same pls send me on shitalghumare123@gmail.com.I would be really thankful to you