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
Debbie@AsymtekDebbie@Asymtek 

Code behind the Clone Button

I want to create a new clone button that doesn't poplulate all the fields of the standard clone button. Does anyone have the apex code behind the standard one that I can copy and modify?

Eager-2-LearnEager-2-Learn

I do not have code for the original Clone button; however, below is code that works for me using a custom clone button to call it.  In addition, this code clones the related Opportunity Partner Record too.  It is an all or nothing process.  Meaning if an issue occurs cloning the opportunity or the opportunity partner(s) then all is rolled back.

 

The code for the custom button is below too.

 

In the select query just add all the fields that you want modify the data.  If you do not want to clone the partner record(s) too just remove that portion of the code.

 

// This class clones an opportunity and all related partner records
public class OppCloneWithPartnerRecsController {
 
    //added an instance varaible for the standard controller
    private ApexPages.StandardController controller {get; set;}
     // add the instance for the variables being passed by id on the url
    private Opportunity opp {get;set;}
 
    // initialize the controller
    public OppCloneWithPartnerRecsController(ApexPages.StandardController controller) { 
        //initialize the stanrdard controller
        this.controller = controller;
        // load the current record
        opp = (Opportunity)controller.getRecord();       
    }
 
    // method called from the VF's action attribute to clone the partners    
    public PageReference oppCloneWithPartners() { 
         // setup the save point for rollback
         Savepoint sp = Database.setSavepoint();
         Opportunity newOpp;
         
         String fmtDate;
         DateTime dt;         

         try {                      
              //Copy the opportunity - ONLY INCLUDE THE FIELDS YOU WANT TO CLONE              
              //WHEN MOVING TO PRODUCTION ADD THESE FIELDS
              // Strenghts__c, Underwriting__c,        

                    opp = [Select o.AccountId, o.Account.Name, 
                                  o.Amount, o.CloseDate, o.Effective_Date__c,                                                          
                                  o.ExpectedRevenue, o.Fiscal, o.FiscalQuarter, o.FiscalYear, 
                                  o.HasOpportunityLineItem, o.Id, o.IsClosed, o.IsDeleted, 
                                  o.IsPrivate, o.IsWon, o.LeadSource, o.Name, o.StageName                                  
                           from Opportunity o
                           where o.Id = :opp.id];


             opp.CloseDate = opp.CloseDate + 365;
             opp.Effective_Date__c = opp.Effective_Date__c + 365;
             
             //format the date for appending to the opp name
             dt = DateTime.newInstance(opp.Effective_Date__c.year(),
                                       opp.Effective_Date__c.month(), 1, 0, 0, 0);            
             fmtDate = dt.format('MM/yy'); 
            
             opp.Name =  opp.Account.Name + ' ' + fmtDate;
             opp.StageName = 'Proposal';
             opp.Products_Sold__c = null;            

             newOpp = opp.clone(false);
             insert newOpp;

             // Copy over the partners to clone
             // Behind the SFDC scenes they actually create the second record on the Partner object
             // and they create the records on the OpportunityPartner object when an insert is executed
             // on the Partner object from their Opportunity page.  
             // Notice the code reads the SFDC OpportunityPartner object and insert into the SFDC Partner
             // object.  If you use the Apex Explorer you will see both objects reflect the same records.  
             // SFDC must have triggers behind the scenes handling this action.             
             List<Partner> insertPartners = new List<Partner>();
             List<OpportunityPartner> partners = 
                     new List<OpportunityPartner>([Select IsPrimary,AccountToId,OpportunityId, Role 
                                                   From OpportunityPartner 
                                                   where OpportunityId = :opp.id and 
                                                         AccountToId <>:newOpp.AccountId]);            
            for(Integer i=0;i<partners.size();i++)
            {
                Partner newPartner = new Partner();
                newPartner.AccountToId = partners.get(i).AccountToId;
                newPartner.OpportunityId= newOpp.Id;
                newPartner.IsPrimary=partners.get(i).IsPrimary;
                newPartner.Role=partners.get(i).Role;
                insertPartners.add(newPartner);                
            } 
            insert insertPartners; 
                       
         } catch (Exception e){
             // roll everything back in case of errors
            Database.rollback(sp);
            ApexPages.addMessages(e);
            return null;
         }
 
         return new PageReference('/'+newOpp.id);
         //return new PageReference('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
    }
    
}

 

 

Custom Clone Button Code with Confirmation:

if( confirm("Sure you want to clone the opportunity an related partner record(s)?") ){
 window.top.location = "/apex/OppCloneWithPartnerRecs?id={!Opportunity.Id}";
}

 The button Display type should be 'Detail Page Button' and Behavior should be 'Execute JavaScript'.  I gave the button label the name 'Clone with Opportunity Partners' but you could call it what you want.


Once all this is created add the button to the opportunity page.

 

 

Hope this helps.  It was from with in these walls that I was able to get this code to work.  What a great bunch of people.

AsymtekAsymtek

Thank you!  I will try it.

Eager-2-LearnEager-2-Learn

I don't know this for a fact but I would think code behind standard buttons is SFDC's and not accessible by customers.  The code that I provided can be customized to update not not update what fields you want to update.  That code doesn't populate anything you do not add to the code; however, at a minimum you will have to include fields that are required by field definition or validation rules.

 

You are able to override the default Clone button with the code that I provided, hide the clone button and create your own with a confirmation button as I had included.


Hope this helps.

DeveloperSFDeveloperSF

Hello,

 

I think I am missing a step. I have the button created and I developed the apex class. When I hit the new button I get a message that says Page oppCloneWithPartners does not exist.

 

I take it I need to create a page - so I did this but it does not give me the standard opp page.

 

Can you please help? I would really appreciate it.

 

Thanking you in advance.

 

 

Eager-2-LearnEager-2-Learn

Good catch.  I forgot to mention the VF page.that is required.  This is all that I done and it is working for me in DEV and TEST Sandbox.  We have not moved it to production and since then we have activated Products in TEST which has its own dropdown button that has two options, "Clone without Products", "Clone with Products".  That has thrown a wrench into what I have already done because now I have to figure out how to override or duplicate cloning of products too!  I have posted a top on that a few days ago.  If you know anything that can help there it would be appreciated.

 

Hope this VF page resolves your missing link.

 

<apex:page standardController="Opportunity"

     extensions="OppCloneWithPartnerRecsController"

     action="{!oppCloneWithPartners}">

     <apex:pageMessages />

</apex:page>

SF-devSF-dev

@Tom, Thanks for sharing this code.

 

My requirement is on cloning Opportunity , I need to clone the partners. The code provided here is exactly  what my requirement is. However I have couple of questions. 

 

In the code we are creating the 'Partner' records by querying 'Opportunity Partner' .

 

Now my question is 

1. Instead of querying 'Opportunity Pratner' , can't  we directly query 'Partner'  as we are inserting Partner ?

2.  In the below code , what is the reason for  condition 'AccountToId <>:newOpp.AccountId'


 new List<OpportunityPartner>([Select IsPrimary,AccountToId,OpportunityId, Role 
                                                   From OpportunityPartner 
                                                   where OpportunityId = :opp.id and 
                                                         AccountToId <>:newOpp.AccountId]);   

 

 

Thanks in advance !

-RM

jayashreejayashree

i am writing a custom clone button.that button will clone a existing record based on the value of a field.my problem is if i am clicking the clone button it is creating a record.but my requirement is it sud create  a record only if click clone and then save button

SantiGalmaSantiGalma
Hi,
I have this custom clone button created by the consultant on my opp object

/apex/Clone2?id={!Opportunity.Id}&childobjecttypes=Service_Line__c&grandchildobjecttypes=Product_Line__c&
Service_Line__c_Name=Service_Name__c&Product_Line__c_Name=Product_Name__c

The problem is that it clone and save it jumping the edit mode.
any idea how to add the edit step to this?

Thanks

SG
 
Georges MardiniGeorges Mardini
Hi,
I have a little question,
i create a new clone button on opportunity, but when i use this button to clone a won opportunity (so the opportunity is closed), my apex code put StageName into the first step but the opportunity is still closed.
What should i do?