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
Brandon WermesBrandon Wermes 

trigger when case status is changed

Hello all,

I am working to write a trigger that will change the owner of a case to the current user when the case status is changed.

Using trigger code found on this forum (credit to jasonkor) I am able to successfully change the case owner when the status is changed. However, since the Trigger is updating the case owner IF the status is equal to In Progress, anytime the case is edited the owner will change.

Ideally, I'd like the owner to be changed only IF the status is edited (use case = multiple users will work a case, but whoever changes status is the new owner).

Here is the trigger:
trigger CaseOwnerUpdate on Case (before update) {

    if (Trigger.new.size() == 1) {  
        // if a Case has been updated to In Progress
        if (Trigger.new[0].Status == 'In Progress') {  
            // Change Trigger.old[0].OwnerId to Current User ID
            Trigger.new[0].OwnerId = UserInfo.getUserId();
        }
    }
}

I realize that the fault lies in the 
if (Trigger.new[0].Status == 'In Progress') {

line, but as I am new to Apex and mostly a point & click admin, I am unsure how to write the trigger to active the owner change only when the case status is changed.

Help is greatly appreciated.

Thank you!
Sumit Kumar Singh 9Sumit Kumar Singh 9
Hello Brandon,
First of all your trigger is not bulkified.
Here, is bulkified trigger and hope it will solve your problem.
trigger CaseOwnerUpdate on Case (before update) {
   for(Case caseRec : Trigger.new) {
       if(Trigger.oldmap.get(caseRec.id).Status != Trigger.newmap.get(caseRec.id).Status && Trigger.newmap.get(caseRec.id).Status == 'In Progress') {
          caseRec.ownerId = UserInfo.getuserId();               
       }
   }
}
Pls, let me know if you need further help.

Thanks,
Sumit Kumar Singh