Monday, 19 October 2015

Automatically fire an assignment rule in salesforce using apex trigger

  1. trigger AutoAssignmentRuleTrigger on Lead (after insert, after update)
  2. {
  3.     List<Lead> leadList = new List<Lead>();
  4.    
  5.     for(Lead currLead : Trigger.New)
  6.     {
  7.         if((Trigger.isInsert && Trigger.isAfter) && currLead.LeadScore__c != null)
  8.         {
  9.             leadList.add(new Lead(id = currLead.id));
  10.         }
  11.         else if((Trigger.isUpdate && Trigger.isAfter) && Trigger.oldMap.get(currLead.Id).LeadScore__c != currLead.LeadScore__c)
  12.         {
  13.             leadList.add(new Lead(id = currLead.Id));
  14.         }
  15.     }
  16.    
  17.     Database.DMLOptions dmo = new Database.DMLOptions();
  18.     dmo.assignmentRuleHeader.useDefaultRule = true;
  19.     Database.update(leadList, dmo);
  20.  
  21. }


In the above trigger, default assignment rule has been been initiated by using the below line,

  1. dmo.assignmentRuleHeader.useDefaultRule = true;

You can also query the assignment rule and set that rule id in code as below,

  1. AssignmentRule AR = [select id from AssignmentRule where SobjectType = 'Lead' and Active = true AND Name = 'Cost Rule' limit 1];
  2. Database.DMLOptions dmo = new Database.DMLOptions();
  3. dmo.assignmentRuleHeader.assignmentRuleId = AR.Id;
  4. Database.update(leadList, dmo);

Reference: 

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...