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
Cheerag VijayaCheerag Vijaya 

Clone Button in VF Page for Replication

I need to create a button in vf page through apex code so that all the details of account and its - contact, opportunity , activity details are replicated - so that an other account gets created with the same account, contact , opportunity , activity details.
For ex., I create an account and contacts and opportunity and activity for that account . By clicking a button  on vf page called - 'Clone' an other account should get created with the same contact, opp., activities. - 'A button for Replication'. It should be done clone method.
parth jollyparth jolly
Here is the 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.


 
Cheerag VijayaCheerag Vijaya
Hey Parth Its the perfetc code. Great!
parth jollyparth jolly
Hi Cheerag,

Pleasure and please return the favor by marking the question as Closed/Resolved by clicking the Best Answer button on the solution so that If anyone have the same concern he/she can get answer as well.