June 14, 2013

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