To start, we have a product that syncs data to and from salesforce via the api. When a record is updating in our platform, the data is pushed to salesforce, when the data is updated in salesforce, it is pushed to our product. The problem we're running into is an infinite loop that is being rather troublesome. Is there a way in SalesForce to determine who is executing a trigger so that when data is updated in our product and pushed to salesforce, the trigger will not fire? I haven't seen an execution information about this before so I'm really not sure on it.
Thanks!
I don't believe there is anything beyond Trigger.isExecuting, which simply tells you whether you are already in a trigger context or if you're coming from Visualforce, the API, or execute anonymous.
One possible solution is to create a custom field that retains the origin of the most recent update. This can then be used to properly route logic within your triggers and avoid calling out when the last update is from your external system. Additionally you can loop through all fields in your Trigger.old and trigger.new to see which fields changed. This way you can avoid further unnecessary syncs to your external system when nothing interesting actually changed on your record (SystemTimeStamp, LastModifiedDate, etc.) Here's a sample of how to do this:
trigger ContactDescribeExample on Contact (before update)
{
// Get describe fields to evaluate old and new triggers with
Map<String, Schema.SObjectField> fldObjMap = Schema.SObjectType.Contact.fields.getMap();
List<Schema.SObjectField> fldObjMapValues = fldObjMap.values();
// Flag to determine if field(s) other than FirstName caused this change (FirstName is just an example)
Boolean hasOtherChange = false;
// Loop through trigger batch
for(Contact c : Trigger.new)
{
for(Schema.SObjectField s : fldObjMapValues)
{
String fldName = s.getDescribe().getName();
// Filter out fields we're not interested in
if(fldName != 'FirstName' && fldName != 'LastModifiedDate' && fldName != 'LastModifiedById' && fldName != 'SystemModstamp')
{
// Check to see if old and new are different
if(c.get(fldName) != Trigger.oldMap.get(c.Id).get(fldName))
hasOtherChange = true;
}
}
}
}