Tuesday, July 4, 2017

Assignment Rules From Apex in salesforce


Running Case Assignment Rules From Apex:


Problem

Running Case assignment rules while inserting a case from Apex.

Description

Case assignment rules allow you to automatically route Cases to the appropriate users or queues. A Case assignment rule consists of multiple rule entries that define the conditions and order for assigning cases. You can create multiple rules (for example, a Standard rule and a Holiday rule), but only one rule can be "active" at a time.
From a standard UI, a user can trigger assignment rules by simply checking the "Assign using active assignment rules" checkbox under the Optional section. The problem arises when your app needs to insert the Case from Apex and wants to trigger assignment rules. Using this script, a Case will be inserted but assignment rules will not be triggered as there is no such field "Assign using active assignment rules" on Case.
//Instance of case
Case newCase = new Case(Status = 'New') ;
//Inserting a Case
insert newCase ;

Solution

A solution is using Database.DMLOptions. The Database.DMLOptions class can provide extra information during a transaction; for example, specifying the truncation behaviour of fields or assignment rule information. For example, the script below is fetching the assignment rules of Case and then creating the DMLOptions for the "Assign using active assignment rules" checkbox.
//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(Status = 'New') ;
//Setting the DMLOption on Case instance
newCase.setOptions(dmlOpts);
insert newCase ;
Now when the Case is inserted using this script, the assignment rules get triggered.

References


User below trigger to fire the assignment rule on case creation via API:

trigger CaseAssignment on Case (after insert) {
    //Variable decleration
    List<Case> caseList = new List<Case>();
    User integrationUserObj = new User();
  
    if(Trigger.isAfter && Trigger.isInsert){
        //Fetching the integration user details
        integrationUserObj = [SELECT Id, Name FROM User where Name = 'Integration User' LIMIT 1];
          
        for (Case caseObj : Trigger.new) {
            if (caseObj.OwnerId  == integrationUserObj.Id) {
                caseList.add(new Case(id = caseObj.id));
            }
        }
  
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.useDefaultRule = true;
        Database.update(caseList, dmo);
    }
}

No comments:

Post a Comment