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
travis.truetttravis.truett 

Opportunity Cloning Trigger

I wrote a trigger that is supposed to clone an opportunity whenever its stage is set to "Closed Won." It's running without errors, but when I create a new opportunity and change its stage to "Closed Won" and then check the list of opportunities, there is no new opportunity. I think I'm cloning the opportunity correctly, but I don't know how to push it to the list of opportunities and give it a name.

here's my trigger:

trigger Create_followup on Opportunity (before update) {

if(Trigger.isUpdate){

List<Opportunity> listOppor = new List<Opportunity>();
for (Opportunity o: Trigger.new){

    if (o.StageName == 'Closed Won' && o.Stage_Change__c == false){

        Opportunity oppNew = o.clone();
        listOppor.add(oppNew);
        o.Stage_Change__c = true;
}

    if(listOppor.size() > 0){
        
        insert listOppor;
}
}
}
}

Thanks in advance for your help! 
Nidhi GuptaNidhi Gupta
Hello,

Your code seems to work in my org, though I did remove code that referenced your custom field.

if(Trigger.isUpdate){

List<Opportunity> listOppor = new List<Opportunity>();
for (Opportunity o: Trigger.new){

    if (o.StageName == 'Closed Won' ){
        Opportunity oppNew = o.clone();
        //oppNew.Name = oppNew.Name  + '_Copy';
        listOppor.add(oppNew);
    }// end if

    if(listOppor.size() > 0){
       insert listOppor;
     }//end if

}//end for
}//end if

Couple of suggestions
1) Its good practice to do insert operation outside for loop
2) You may update the name of cloned opportunity using code oppNew.Name = oppNew.Name  + '_Copy';
3) The old and new records should be compared to see if the value of a field has chnaged in given transaction.I am not able to interpret the significance of Stage_Change__c, may be you are using this field for same purpose as well

Hope this helps

Regards
Nidhi