Clone Multiple sObjects and their child records by chaining one after other
In Order to clone records, we need some template records to clone. For the rest of the topic we will refer them as “template records”, and newly created records as “cloned records”
When we clone records in apex using the standard sObject clone method, all the fields present on the queried object copy over to the cloned record, but a major part which left behind is the child records of the template record.
Here’s a demo code (CloneSobjectDemo.demo()) of how would you use the CloneSobjects library class to chain record cloning one after another.
Notice how we first query all the template records that are supposed to be cloned, then we build map for each cloned that will serve as passing function as an parameter to a method, because in case of each field we are achieving different function.
The lib has two standard classes defined that have different jobs depending on the requirement. You can write your own class (implementation of OverRideSObjectFields interface) to achieve something unique
(like append “ — Cloned” in the name fields)
One of the standard classes is ReturnParentFieldFromTemplate which serves the main goal of getting the right parent field linked to the right child, making the interrelations between the sObjects count.
Needless to say, we have to insert all the parent (independent) records first, in this case all Account records, then Contact and then Opportunity.
Lastly attached together is a TestClass to make sure we have apt amount of code coverage, because of TDD.