Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a record is being cloned in trigger

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.

like image 942
Daniel Ballinger Avatar asked Jul 29 '12 06:07

Daniel Ballinger


People also ask

How do you check if a record is cloned in Apex?

If you are willing to write Apex Code then you can write a trigger where on insert you can check if an object is cloned (via the isClone() function on sObject) and then use the getCloneSourceId() function (on sObject) to find the originator and set a checkbox to true on that object.

What happens when you clone a record in Salesforce?

If the record you're cloning contains a field you have read-only access to, the field in the new record is blank. However, if a related record contains a field you have read-only access to, the field value is copied into the new record. Save the new record.

Can we access record ID before trigger insert?

In before insert - id value wont be there.... since the record is not inserted into database. in before update - id value will be there and you will be albe to use that id for calcualtion. Only in After Insert you will get the id of that record.


1 Answers

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

like image 92
Doug Ayers Avatar answered Oct 27 '22 13:10

Doug Ayers