function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pokalakari nagapokalakari naga 

How to clone the record along with it's related list

Hi all,

I have two custom objects with lookup firlter relationship when i cloone the Custom object A then the related list records also need to be clone. How can we achive this. 
Can anyone help me overhere.

Thanks in advance.

Regards,
naga.
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Pokalakari,
  • To clone a record with related records in Salesforce.
Sample Code:
Visualforce page:

<apex:page controller="Sample" sidebar="false">

<apex:form >
    <apex:pageblock >
        <apex:pageblockSection >
            <apex:pageblockSectionItem >Enter the Account Id:</apex:pageblockSectionItem>
            <apex:pageblockSectionItem ><apex:inputtext value="{!idOfRec}" /></apex:pageblockSectionItem>            
        </apex:pageblockSection>
        <apex:pageblockButtons >
            <apex:commandButton value="Clone" action="{!cloneRec}"/>
        </apex:pageblockButtons>
    </apex:pageblock>   
</apex:form>

</apex:page>
 
Apex Controller:

public class Sample
{   
    public String idOfRec {get;set;}
   
    public Sample()
    {
    }
   
    public void cloneRec()
    {
        List<Contact> cons = new List<Contact>();
        Account acc = [SELECT ID, Name FROM Account WHERE Id = : idOfRec];
        Account accCopy = acc.clone(false,true);
        insert accCopy;
        List<Contact> con = [SELECT Id, LastName, AccountId FROM Contact WHERE AccountId = : acc.Id];
        for(Contact c : con)
        {
            Contact conCopy = c.clone(false,true);
            conCopy.AccountId = accCopy.Id;
            cons.add(conCopy);
        }
        insert cons;
    }
}

here I have cloned Account record along with Contacts.
Hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Thanks
Rahul Kumar