+ Start a Discussion

Deep clone available methods help to get started

Hi folks
My newbie journey continues. Now I'm trying to write a deep clone button. I'm not sure of the available methods/best practices.  Here is what I want in process/pseudo code form and I'd be grateful for help in terms of class/methods to use and order of events.

Here is an object chart of the relevant objects:

object chart
  1. Button on parent is clicked. (AM__c SOjbect).
    1. AM record is cloned in it's entirety and Name is changed to a specific concatenation.  And along with it the following are cloned in correct 'generations':
      1. PF__c child records attached to this particular AM__c SObject record (via Join object) are copied with all their fields.
        1. G__c grandchildren records (via Join PF_G) attached to each PF__c record are copied with all their fields
          1. F__c great grandchildren records (via Join_G_F) records that are attached 
Once all of that is cloned, I want to lock down either this version or the old version to read only.
Roy LuoRoy Luo
I just finished my generic deepclone utility and here are the basic ideas:

1. Use DescribeSObjectResult to build the sObjectType tree
2. Flat out the tree to a list of sObjectType in the order of cloning, for your instance here it would be AM__c, PF__c, G__c, F__c, then the join items
3. Implement a Stateful Batchable for cloning
4. Start the batchable on the flat list of sObjectType, always grab the first element from the list
5. When the batchable job is completed, remove the first item from the list then kick off another batchable job
6. When the list is empty, the deepclone is done then send an email notification

As a side note, if you have a self-referencing customObject, you would need to copy the items layer by layer.
Make sure make your batchable implementation stateful, thus you could carry along an SourceIdToNewItemIdMapping across batches to setup the join relationship between the new copies.

BTW this is not an easy task.