How 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:pageblockButtons >
            <apex:commandButton value="Clone" action="{!cloneRec}"/>


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;
        insert cons;

here I have cloned Account record along with Contacts.



  1. Very nice work. I am sure developers will be creative on how they want to clone records using your code.

    If you do not want to write code and have need for cloning any object, you take a look at this paid app on AppExchange: which allows you to:
    - Clone any object, standard or custom with any related list
    - Configure which fields to override
    - Provide default field values
    - Select child records to clone

    Hope it helps someone.

  2. Hi,

    I have one doubt. Suppose if we are cloning multiple parent record using list then how to clone corresponding related list records.

  3. How to auto-populate account id instead of entering it manually in Account id field on vf page? Also, after clicking on clone, how could it would redirect to the new cloned page?

    1. After insert cons;

      pagereference pg=new pagereference('/';
      return pg;

    2. Did you get that autopopulate id .