How to Clone a Record with Related Lists?

How to Clone a Record with Related Lists?

On March 6, 2025, Posted by , In Apex,Salesforce Technical Questions, With Comments Off on How to Clone a Record with Related Lists?
How to Clone a Record with Related Lists

Question:

I need to clone all Account records along with their associated Contact records. I am using the clone() method in Apex for this. Below is the code I have written:

List<Account> accListToClone = new List<Account>();
List<Contact> conListToClone = new List<Contact>();
Set<Id> accIdSet = new Set<Id>();
Map<Id, List<Contact>> mapOfAccIdVsContact = new Map<Id, List<Contact>>();

List<Account> accs = [SELECT Id, Name, Phone FROM Account];
for (Account acc : accs) {
    accIdSet.add(acc.Id);
}

List<Contact> cons = [SELECT Id, FirstName, LastName, Phone, Account.Id FROM Contact WHERE Account.Id IN :accIdSet];

for (Contact con : cons) {
    if (mapOfAccIdVsContact.containsKey(con.Account.Id)) {
        mapOfAccIdVsContact.get(con.Account.Id).add(con);
    } else {
        mapOfAccIdVsContact.put(con.Account.Id, new List<Contact>{con});
    }
}

for (Account acc : accs) {
    Account accClone = acc.clone(false, true, false, false);
    accClone.Name = acc.Name + ' Clone';
    accListToClone.add(accClone);

    List<Contact> conList = mapOfAccIdVsContact.get(acc.Id);
    for (Contact con : conList) {
        Contact conClone = con.clone(false, true, false, false);
        conClone.FirstName = con.FirstName + ' Clone';
        conClone.AccountId = accClone.Id; // How to get the cloned Account ID here?
        conListToClone.add(conClone);
    }
}

insert accListToClone;
insert conListToClone;

I am unable to figure out how to associate the cloned contacts with the corresponding cloned accounts. Since the cloned account IDs are only available after insertion, I would need to insert each account within the loop, which is a bad practice. What is the best way to solve this?

Answer:

When you insert a record, Salesforce assigns it an ID, which is stored in the object in Apex. Since accListToClone maintains the same sequence as accs, you can use a for loop to map the original account IDs to their corresponding cloned account IDs.

Master Salesforce with expert-led training at CRS Info Solutions in  Salesforce training in Hyderabad. Gain hands-on experience in Admin, Developer (Apex), and Integration—join a free demo today!!!

Example

insert accListToClone;

Map<Id, Id> originalToClonedIdMap = new Map<Id, Id>();
for (Integer i = 0; i < accs.size(); i++) {
    originalToClonedIdMap.put(accs[i].Id, accListToClone[i].Id);
}

for (Contact con : cons) {
    Contact conClone = con.clone(false, true, false, false);
    conClone.FirstName = con.FirstName + ' Clone';
    conClone.AccountId = originalToClonedIdMap.get(con.AccountId);
    conListToClone.add(conClone);
}

insert conListToClone;

Explanation: The code first inserts the cloned accounts, allowing Salesforce to generate new IDs. It then creates a mapping between the original and cloned account IDs using their list positions. Finally, it clones the contacts, assigns them the correct cloned account IDs from the map, and inserts them into the database.

Alternate Approach:

Another way to handle this scenario is by using the Database.insert method with the allOrNone parameter set to false. This ensures that even if some records fail to insert, the rest are successfully committed, which can be useful in large-scale cloning operations.

First, insert the cloned accounts and retrieve their new IDs immediately using Database.insert(accListToClone, false). Then, construct a mapping between the original account IDs and the cloned account IDs. After that, clone the contacts and set their AccountId values accordingly before inserting them.

Example

List<Account> accListToClone = new List<Account>();
List<Contact> conListToClone = new List<Contact>();
Set<Id> accIdSet = new Set<Id>();
Map<Id, List<Contact>> mapOfAccIdVsContact = new Map<Id, List<Contact>>();

List<Account> accs = [SELECT Id, Name, Phone FROM Account];
for (Account acc : accs) {
    accIdSet.add(acc.Id);
}

List<Contact> cons = [SELECT Id, FirstName, LastName, Phone, AccountId FROM Contact WHERE AccountId IN :accIdSet];

for (Contact con : cons) {
    if (!mapOfAccIdVsContact.containsKey(con.AccountId)) {
        mapOfAccIdVsContact.put(con.AccountId, new List<Contact>());
    }
    mapOfAccIdVsContact.get(con.AccountId).add(con);
}

for (Account acc : accs) {
    Account accClone = acc.clone(false, true, false, false);
    accClone.Name = acc.Name + ' Clone';
    accListToClone.add(accClone);
}

// Insert accounts and get new IDs
Database.insert(accListToClone, false);

Map<Id, Id> originalToClonedIdMap = new Map<Id, Id>();
for (Integer i = 0; i < accs.size(); i++) {
    originalToClonedIdMap.put(accs[i].Id, accListToClone[i].Id);
}

// Clone and associate contacts
for (Contact con : cons) {
    Contact conClone = con.clone(false, true, false, false);
    conClone.FirstName = con.FirstName + ' Clone';
    conClone.AccountId = originalToClonedIdMap.get(con.AccountId);
    conListToClone.add(conClone);
}

Database.insert(conListToClone, false);

Explanation: The code retrieves all Account records and their related Contacts, then clones the Accounts while storing a mapping of original to cloned Account IDs. After inserting the cloned Accounts, it uses the mapping to assign the correct AccountId to each cloned Contact before inserting them. This ensures that Contacts remain properly linked to their respective cloned Accounts without violating best practices like inserting records inside loops.

Launch Your Salesforce Career in Hyderabad’s Booming IT Hub

Hyderabad has emerged as a leading hub for IT and cloud technologies, with Salesforce driving digital transformation across industries. Salesforce training in Hyderabad As businesses increasingly adopt Salesforce for CRM, AI, Integration, and Lightning solutions, the demand for skilled professionals continues to surge. Top companies like Deloitte, Accenture, Infosys, TCS, and Wipro actively hire certified Salesforce experts, making professional training a critical step toward securing high-paying job opportunities.

For those looking to build a successful career in Salesforce, choosing the right training institute is essential. CRS Info Solutions offers industry-focused Salesforce training in Ameerpet, covering all key modules, including Admin, Developer (Apex), and Integration. With hands-on projects and real-world scenarios, this expert-led program equips you with the skills needed to earn certification and excel in Hyderabad’s competitive job market. Now is the perfect time to invest in your future—enroll today and take the next step in your Salesforce journey!

Comments are closed.