+ Start a Discussion
Nabeel Munir 9Nabeel Munir 9 

How can I check if a field is already updated before firing a trigger

Hello, I have a situation where I need to check if a field is already updated or not before firing a trigger.
Meaning,
I have just finished apex specialist super badge where everytime a case is updated to closed, a new maintenance request is made automatically. But, what if the status is already updated to closed and i go ahead edit it and save it without doing anything, in this case another maintenance request will be made which should not be made.
So, I should case.status field is already updated to closed or not. How can i achieve this in trigger. I want that trigger does not fire if the field is already updated.

Below is the trigger that i have tried but i m really not sure about it.

trigger MaintenanceRequest on Case (before update,after update) {
    // call MaintenanceRequestHelper.updateWorkOrders
    if(trigger.isBefore && trigger.isUpdate)
    {
        for(Case c: trigger.old)
        {
            if(c.Status!='Closed')
            {
              MaintenanceRequestHelper.updateWorkOrders();          
            }
        }
    }
      
}
Best Answer chosen by Nabeel Munir 9
Andrew GAndrew G
for (Case c : trigger.new) 
{
  if ( (trigger.oldMap.get(c.Id).Status != c.Status) && c.Status = 'Closed') ) 
  { 
    //the status has changed from something to Closed ... so do stuff
  }
}
Hi Nabeel

Using the oldMap values for comparison works well for this situation.

Regards
Andrew
 

All Answers

Andrew GAndrew G
for (Case c : trigger.new) 
{
  if ( (trigger.oldMap.get(c.Id).Status != c.Status) && c.Status = 'Closed') ) 
  { 
    //the status has changed from something to Closed ... so do stuff
  }
}
Hi Nabeel

Using the oldMap values for comparison works well for this situation.

Regards
Andrew
 
This was selected as the best answer
Nabeel Munir 9Nabeel Munir 9
Thanks andrew, This is exactly what i was looking for.