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
RayAllenRayAllen 

How to create a duplicate opportunity from previous when the opp stage is equal to a certain stage

Hello,

 

I want to create a duplicate opportunity, for example, if opportunity stage is equal to “won” , I want it to be able to create an exact replica of the old opportunity.  I know I’ll have to make a workflow and use apex code.

 

How can I write the formula for this?

RayAllenRayAllen

Also, I would want it to be fully automated.

TheDoctorTheDoctor

This would need to written as a trigger. Do some research on the sObject Clone method. 

I haven't tested this, but something along these lines should do the trick... or get you cklose at least:

trigger cloneWonOppty on Opportunity <after update> {

    List<Opportunity> oppList = new List<Opportunity)();

    for(Opportunity opp: trigger.new){

        Opportunity o = sObject.clone(opp);
        oppList.add(o);

    }

    if(oppList.size() > 0){

        insert oppList;

    }

}

 

 

 

SFDC_LearnerSFDC_Learner
trigger cloneWonOppty on Opportunity(after update) {
 
    List<Opportunity> oppList = new List<Opportunity>();
 
    for(Opportunity opp: trigger.new){
        if(opp.stageName == 'closed own'){
            Opportunity objopp = opp.clone(false);
            oppList.add(objopp);
        }
 
    }
 
    if(oppList.size() > 0){
 
        insert oppList;
 
    }
 
}
RayAllenRayAllen

Thanks guys really appreciate it. 

 

Another question, do I have to add an Apex test class? What would that formula look like?

 

Thanks

SFDC_LearnerSFDC_Learner

Here is the test code:

 

 

@isTest

public class OppTriggerTestClass{
Test.startTest();
// Create Opportunity Record with all Required fields
Opportunity objOpp = new Opportunity();
objOpp.name ='Test Opportunity';
objOpp.stagename='Needs Analysis';
insert objOpp;
 
// Update the same Record with stagename 'ClosedOwn'
objOpp.stagename ='Closed Own';
update objOpp;
 
 
Test.stopTest();
}