Custom button on Opportunity to clone opportunity with its related List (object)

Create a new Detail Page Button on the Opportunity object.
Set Behavior to Execute JavaScript and Content Source to OnClick JavaScript
Paste the Below snippet of code in the window

{!REQUIRESCRIPT("/soap/ajax/39.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/39.0/apex.js")} 
var retStr; 
retStr = sforce.apex.execute("CloneOpportunitywithRelatedObject","cloneOpportunity", 
{oppId:"{!Opportunity.Id}"}); 
location.replace('/' + retStr); 


Create a new Apex class and paste the below snippet of code

global class CloneOpportunitywithRelatedObject {     webservice static Id cloneOpportunity(Id oppId) //  pass parameters     {         List < Related_Object__C > relatedList = new List < Related_Object__C > (); 
// query all the fields you need to clone          Opportunity opp = [SELECT ID, CloseDate, StageName, Type, Name FROM Opportunity                                        WHERE Id =: oppId];         Opportunity oppCopy = opp.clone(false, true); / /     Append the new opportunity name with Clone Text          oppCopy.Name = opp.Name + 'Clone';         insert oppCopy;         //cloning Related object record         for (Related_Object__C  p: [SELECT Id, Customer_Part_Number__c FROM Related_Object__C                                                     WHERE Opportunity__c =: opp.Id]) {             Related_Object__C relatedCopy = p.clone(false, true);             relatedCopy .Opportunity__c = oppCopy.Id;             relatedList.add(relatedCopy);         }         insert relatedList;         return oppCopy.Id;     } } Note : Add the detail Page button on the Opportunity Layout 
Enjoy Coding !!

Comments

Post a Comment

Popular posts from this blog

Test-Driven Development in Salesforce

Setting a default 'From' address when sending an email from Cases

Email Messaging from Salesforce