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:


No comments:

Post a Comment