Just update when a specific field changes

I created a trigger to open a case in my account if (Atribuido__c == 'SIM')

I want the trigger to fire just when this field is updated.

If this field is already updated and I update any other fields in my Account the trigger should not.

The trigger that I’ve done is firing always when I update my account if (Atribuido__c == 'SIM')

trigger CriarCaseAccount_AR on Account (after update) {
    List<Case> Cases = new List<Case>();
    List<Account> act = Trigger.new;

    for (Account ct : act) {
        if (ct.Antecipado__c == 'SIM' && ct.RecordTypeID == '012U00000000vYx' || ct.Antecipado__c == 'AR' && ct.RecordTypeID == '012U00000000vYx'){
            Case c = new Case(
                AccountID = ct.id,
                RecordTypeID = '012U000000011yC',
                Motivo__c = 'Formandos AR',
                Prazo_para_resolucao__c = Date.today(),
                Description = 'Montagens',
                Subject = ct.id,
                Ownerid = '005U0000001KraS'
            );

            cases.add(c);
        }
     }

     insert cases;
}

How I determine the trigger just fire when this specific field is updated?

Thanks Phil !

I just made some changes and works perfectly !

I was trying to fire my trigger just when “Antecipado” == ‘SIM’ or ‘AR’.
If this field is already ‘SIM’ or ‘AR’ and I update another field in my Account.
The trigger can’t be fired.

So:

for (Account acc: Trigger.new) {
    Account oldAccount = Trigger.oldMap.get(acc.ID);

    if (acc.Antecipado__c != oldAccount.Antecipado__c) {
        If (acc.Antecipado__c == 'SIM' || acc.Antecipado__c == 'AR') {

        }
    }
}

Answer

For this, you can reference the Trigger.oldMap and Trigger.newMap map collections. So, you can compare old values with new values. For example:

for( Id accountId : Trigger.newMap.keySet() )
{
  if( Trigger.oldMap.get( accountId ).Antecipado__c != Trigger.newMap.get( accountId ).Antecipado__c )
  {
     // do something here because your field has changed
  }
}

So, the Trigger will always ‘fire’ but you will only act upon it if the new and old values are different (i.e. if the user updated the value).

Attribution
Source : Link , Question Author : Everton CP7 , Answer Author : Phil Hawthorn

Leave a Comment