Print this page

Cloning a record with limited fields

Knowledge Article Number 000227675
Description With the standard clone button, every field of the record gets cloned. By creating a standard clone button we can clone only the fields that are needed as per business requirements.
Resolution In this sample scenario the custom button is created on lead object. The visualforce (VF) page has a standard controller as lead and an extension as a custom class that has been created to achieve the required functionality.  The sample will clone only the fields that are referenced on the VF page.

Note - Special care with the required fields should be taken. 

When you click the custom button on the record detail page, it will take you to the VF page and when the associated extension controller get initialized it picks up the field that are referenced in the VF page and the "clone lead" button will insert the record. 

To accomplish this Task we have to do 3 things. 

(1) Create a VF page with standard controller as lead and apex class as extension. 
===================================================================
<apex:page standardController="lead" extensions="customcloneLead">
<apex:form >
<apex:pageBlock title="Lead details">
<apex:pageBlockSection title="My Content Section" columns="2">
<apex:inputField value="{!lead.company}" />
<apex:inputfield value="{!lead.firstname}"/>
<apex:inputfield value="{!lead.lastname}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons>
<apex:commandButton action="{!clonelead}" value="save clone"/>
</apex:pageBlockButtons>
        </apex:pageBlock>
</apex:form>
</apex:page>

(2) Create a apex extension class. 
=============================
public class customcloneLead{
private lead l;
public customcloneLead(apexpages.standardcontroller std){
this.l = (lead)std.getrecord();
}

public void clonelead(){
lead l1 = new lead();
l1 =l.clone();
insert l1;
}
}


(3) Create a custom button on the Lead object which can be an onclick javascript button depending on your needs. Add that button in the layout. 
Sample Javascript Button:
=====================
window.location.href = "/apex/customcloneLead?id={!Lead.Id}";

Note - you can modify the javascript according to the needs of your business use case. 

Disclaimer: This is only a sample code and you can modify and use it on your discretion by testing the use case in your sandbox. 


 




promote demote