0

I need to clone all Account records along with their contact records. I'm using 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 Account clone record ID here?
        conListToClone.add(conClone);
    }
}

insert accListToClone;
insert conListToClone;

I'm not able to figure out how to link the cloned contact's account Id with the cloned account Id. I would need to insert the cloned account record inside the for loop which is a very bad practice. What is the work around for this?

1 Answer 1

1

Remember that when you insert a record, the ID is returned into that object in Apex.

Also, your accListToClone list will be in the same sequence as your accs list.

That means you can build a "traditional" for loop on the accs list to build a map where the original account IDs are the keys and the cloned account IDs are the values.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .