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
dev2014dev2014 

Assigning a specific type of lead to a specific Queue

Hi,

We are trying to complete the final  part of the logic  of our Apex trigger for a client . We were able to successfully implement the first part of the  logic where  the Apex trigger  automatically  takes  a lead that  is above 500k and has the  picklist field value of  "Finance"  and  automotically creates a task to the lead  creator and owner.

The final part of the business logic we are trying to implement now is to assign the above 500k and finance vertical to the "Financial  expertise"  team Queue and create a task for this Queue team .

if (l.AnnualRevenue >= 500000 & l.Vertical__c == 'Finance') { 

then

Assign lead follow up task to the the "Financial Expertise" Queue

Below is the code we have got so far for the first conditional part of the logic. (We had to switch the object from the Opportunity objet to the Lead Object since you can't create a Queue on the Opportunity object)

 I guess one way to do it is to assign a lead owner value to the "Finance Expertise" Queue ID.

I created a pick list based "vertical "field on the Lead  object and a created  Queue named "Financial Expertise" based on the Lead and Activity objects for this purpose. (See screenshots below)

I would appreciate your code input on this use case or code reference to similar use case where you assign the lead and task to a specific Queue. This is my first Salesforce project so I appreciate your input and help on this.

trigger LeadCreation on Lead (after insert) {
    
    // If tasks are to be created then save them in a separate set and run dml operations outside loop statements   
    List<Task> tList = new  List<Task>();
    Map<Id, Lead> leadMap = new Map<Id, Lead>();
    
    //loop through all new Leads  saved
    for(Lead l: Trigger.new)
    {
        // if the Lead amount is greater than 500000 AND Lead  Vertical = Finance 
        if (l.AnnualRevenue >= 500000 & l.Vertical__c == 'Finance') {

            //assign lead to financial expertise team and create a task for the finacial expertise queue ...
            Task T        = new Task();
            T.Type        = 'Email';
            T.Description = 'A lead was created with amount  of  above 500,000 in your speciality field';
            T.OwnerId     = l.OwnerId;
            T.WhatId      = l.Id; //record id
        
            // DO NOT RUN DML OPERATIONS INSIDE FOR LOOPS            
        tList.add(T);
        leadMap.put(l.Id,l);
    }
        else {
            // if the annual amount is less than 500000 and not financial vertical do nothing ....
        }
    }
    
    if(tList!=null && !tList.isEmpty()){
    LeadTriggerHelper.createTasks(tList, leadMap);
    }
}
public class LeadTriggerHelper {

	
	public static void createTasks(List<Task> tList, Map<Id, Lead> leadMap){
		Set<String> tIds = new Set<String>();
		try{
		
		    Database.SaveResult[] srTask  = Database.insert(tList, false);

			for (Database.SaveResult sr : srTask) {
				if (sr.isSuccess()) {
					// Operation was successful, so get the ID of the record that was processed and fire an email
					System.debug('Successfully created the task. ID: ' + sr.getId());					
					tIds.add(sr.getId());
				}
				else {
					// Operation failed, so get all errors                
					for(Database.Error err : sr.getErrors()) {
						System.debug('The following error has occurred.');                    
						System.debug(err.getStatusCode() + ': ' + err.getMessage());
						System.debug('Task fields that affected this error: ' + err.getFields());
					}
				}
			}
			
			if(tIds!=null && !tIds.isEmpty()){
				for(Task tObj : [SELECT Id, What.Name, WhatId FROM Task WHERE Id IN :tIds]){
					Lead leadObj = leadMap.get(tObj.WhatId);
					SendEmailNotification(leadObj.OwnerId, 'Finance Lead TASK WAS CREATED FOR YOU ON SALESFORCE  !!!', 'GO GETHEM', tObj.WhatId, tObj.What.Name);
				}
			}
		}
		catch(Exception err){
			system.debug('\n Error while creating tasks. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}
	}
	
	public static void SendEmailNotification(Id SendTo, string Subject, string BodyText, String LinkURL, String LinkLabel){
		try
		{
			Messaging.reserveSingleEmailCapacity(1);
			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
			mail.setTargetObjectId(SendTo);
			mail.saveAsActivity = false;
			mail.setSenderDisplayName('Salesforce custom big deal alert');
			mail.setSubject(Subject);

			if (LinkURL != null) {
				mail.setHtmlBody(BodyText + '<br />' + 'Click for details : ' + '<a href=' + LinkURL + '>' + LinkLabel + '</a>');
			}
			else {
				mail.setHtmlBody(BodyText);
			}
			Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
		}
		catch (Exception err) { 
			system.debug('\n Error while sending email. \n'
                                  + err.getMessage() + ' \n'
                                  + err.getStackTraceString());			
		}

	} 


}
User-added image

User-added image
ShashForceShashForce
Hi,

Like with opportunities, you cannot assign tasks to a queue. Here is an existing feature request: https://success.salesforce.com/ideaview?id=087300000007HC0AAM

As a workaround, you can probably get the list of users in the queue and assign separate tasks to each of them.

Thanks,
Shashank
Bryan Revelant 18Bryan Revelant 18
Actually, I found that creating the workflow rule to change owner ship of the record to the Queue and then have a rule that sends the task does not work either. 

My Rule declarativly
If name = null 
change owner to queue
update a check box = true 

sperate rule 
if check box = true 
send task to the owner of the record.