0

I am currently practicing apex and I have a situation. I am firing the trigger every time the case status is updated to "Closed". the trigger creates a new request every time the status is updated to "Closed". This works fine. But, what if i go on and press edit for the same case and save it without doing anything. In that case it will create a new request for the same case which it should not because a request for the same case is already created. How can I check that if the case status is already updated to closed and and prevent the trigger from firing in that case.

Below is what I have tried to check the status of the case but as far as i understand, it only checks new and old values.

 public static void alreadyUpdateCheck(Map<Id,Case> OldMap,Map<Id,Case> NewMap)
   {
       for(Case c: newMap.values())
       {
           if(OldMap.get(c.Id).Status!=NewMap.get(c.Id).Status)
           {
               //Do something
           }
       }
   }

and below is ape trigger.

trigger MaintenanceRequest on Case (before update,after update) {
     if( trigger.isUpdate)
    {
       MaintenanceRequestHelper.alreadyUpdateCheck(Trigger.oldMap,Trigger.newMap);          
    }

}
1

You just need to update your alreadyUpdateCheck to ensure that the status isn't already Closed:

public static void alreadyUpdateCheck(Map<Id, Case> oldMap, Map<Id, Case> newMap) {
    for (Case c: newMap.values()) {
        if (oldMap.get(c.Id).Status != 'Closed' && c.Status == 'Closed') {
           // Generate the request
        }
    }
}

This says the status must have changed to Closed from something else.

  • how about (oldMap.get(c.Id).isClosed!= c.isClosed ? – Pranay Jaiswal Aug 1 at 14:32
  • @Phil W, so, in that case the trigger should not fire and create a duplicate request for the same case because it is not changing from something else to closed, it is already closed and it will not create a duplicate request. I m gonna go ahead and try what you have suggested. – Nabeel Munir Aug 1 at 14:36
  • The trigger will always actually fire (this is how Salesforce works) but the creation of the request is only going to happen when the case is closed and not at some later point. – Phil W Aug 1 at 17:00
  • @PranayJaiswal, certainly using isClosed (assuming that exists, I haven't checked the schema for Case - we don't use them in our product) is cleaner but what you have suggested would create a request when a case is closed AND when a case is "unclosed" (if that is permitted). – Phil W Aug 1 at 17:02
  • @PhilW my bad, my intent was to show use of isClosed. – Pranay Jaiswal Aug 1 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.