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: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.

Output:


5 comments:

  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: https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000B39tWEAR 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.

    ReplyDelete
  2. Hi,

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

    ReplyDelete
  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?

    ReplyDelete
    Replies
    1. After insert cons;

      pagereference pg=new pagereference('/'+accCopy.id);
      pg.setredirect(true);
      return pg;

      Delete
    2. Did you get that autopopulate id .

      Delete