Showing posts with label dipak. Show all posts
Showing posts with label dipak. Show all posts

Tuesday, May 29, 2012

Assignment rule in a trigger

                                   
The objective is to have assignment rules to be fired on a  record creation. 
But, the assignment rule only can be fired on UPDATE operation inside the trigger.
Because when we try to perform DML operation in trigger.new or trigger.old , It throws exception

"Execution of AfterInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old:"

The rule can be assigned only when using "update" DML in an "after insert" trigger.
So the logic should be  in AFTER trigger collect the record Ids , and then SELECT the records & try to UPDATE the same .


trigger caseAssignment on Case (after insert) {

        List<Id> caseIds = new List<Id>{};
        for (Case caseObj:trigger.new)
            caseIds.add(caseObj.Id);
     
        List<Case> caseList = new List<Case>{};
        for(Case myCase : [Select Id from Case where Id in :caseIds])
        {
            Database.DMLOptions dmo = new Database.DMLOptions();

            dmo.assignmentRuleHeader.useDefaultRule = true;
            myCase.setOptions(dmo);
         
            caseList.add(myCase);
        }
        Database.upsert(caseList);
}