Detect when a record is being cloned in trigger

Daniel Ballinger picture Daniel Ballinger · Jul 29, 2012 · Viewed 8.3k times · Source

Is there a way to detect that a record being inserted is the result of a clone operation in a trigger?

As part of a managed package, I'd like to clear out some of the custom fields when Opportunity and OpportunityLineItem records are cloned.

Or is a trigger not the correct place to prevent certain fields being cloned?

I had considered creating dedicated code to invoke sObject.Clone() and excluding the fields that aren't required. This doesn't seem like an ideal solution for a managed package as it would also exclude any other custom fields on Opportunity.

Answer

Doug Ayers picture Doug Ayers · Sep 13, 2016

In the Winter '16 release, Apex has two new methods that let you detect if a record is being cloned and from what source record id. You can use this in your triggers.

  • isClone() - Returns true if an entity is cloned from something, even if the entity hasn’t been saved.
  • getCloneSourceId() - Returns the ID of the entity from which an object was cloned.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm#apex_System_SObject_getCloneSourceId

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm#apex_System_SObject_getCloneSourceId