html code

Run Assignment Rule While Creating Lead or Case

With help of “Database.DMLOptions” standard class, we can achieve the requirement as below:

Lead Example

//Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Lead' and Active = true limit 1];

//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;

Lead newLead = new Lead (LastName= 'abc', Emmail='ayub@tenetizer.com') ;
//Setting the DMLOption on Case instance
newLead.setOptions(dmlOpts);
insert newLead;

Case Example

//Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];

//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;

Case newCase = new Case(Subject='Test Case', Status = 'New') ;
//Setting the DMLOption on Case instance
newCase.setOptions(dmlOpts);
insert newCase ;