+ Start a Discussion
Greg RohmanGreg Rohman 

Preventing an Insert/Update trigger based on value of a field



I'm currently updating my Salesforce data from a mySQL database utilizing a 3rd party integration tool. There are some records, though, that may exist in the mySQL database that I don't want updated in Salesforce. Is there some way to perhaps set a flag in a Salesforce record that would prevent updated information from populating in Salesforce? Perhaps comparing Trigger.Old and Trigger.New and rolling back to the previous values?






Yes, that's exactly what you'd do. You'd want something like:


trigger SelectiveImport on Opportunity (before update) {
for (Opportunity new_o : Trigger.new) {
if (new_o.DoNotUpdate__c) {
new_o.Field1__c = Trigger.oldMap.get(new_o.id).Field1__c;

  • I've used Opportunity in this example, you could use any object
  • You only need this logic for before update, since you need an existing record to check for the flag
  • The field you want to revert is called Field1__c in this example
  • I use Trigger.oldMap.get(Id) because I once read that there's no guarantee that Trigger.new[] exactly matches Trigger.old[], but that might be old-fashioned of me


That technique is very useful for 'overriding' required fields. For example, upserting an Opportunity requires a Close Date and StageName. If you don't want to override them during the import, use the above logic to revert the values back to their current value.