+ Start a Discussion
John NeilanJohn Neilan 

Trigger Issue


I created the trigger below to create a new Opportunity when an existing Opportunity reaches the Closed Won stage.  I have 2 issues.

1)  On the line where I create the new Opportunity's name, the Account Name from the previous Opportunity is not coiming through.

2)  The trigger is actually creating 4 Opportunities instead of just 1.

Does anyone know how to fix these?  Thanks,

// Automatically create an open renewal Opportunity
trigger RenewalOpp on Opportunity(after update) {

  List<Opportunity> newOpp = new List<Opportunity>();
  for (Opportunity opp : Trigger.new) {
  IF(opp.StageName == 'Closed Won'){
    Opportunity renewalOpp = opp.clone(false);
    renewalOpp.Name = opp.Account + ' - Renewal (' +opp.Renewal_Date_Year__c + ')';
    renewalOpp.StageName   = 'Active Discussions';
    renewalOpp.CloseDate   = opp.Renewal_Date_Next__c;
    renewalOpp.Amount = opp.Amount;
    renewalOpp.Effective_Date__c  = opp.Renewal_Date_Next__c;
    renewalOpp.Renewal__c = 'Yes';
    renewalOpp.Renewed_Opportunity__c = opp.Id;
    renewalOpp.Probability = 5;
  IF(newOpp.size() > 0)
  insert newOpp;


Best Answer chosen by John Neilan
kevin lamkevin lam
Yes, creating a map is an option, another is use a formula field to store the account name.

All Answers

You should probably try before update for the first issue. 
For the second issue, there may be other triggers in your org that is cause recursion. Setup debug logs to trace.
kevin lamkevin lam
1) You can get to the Account Name with opp.Account, you need to query it separately.
2) It's probably because of workflow field updates, which cause the trigger to be run again. You can confirm this in the debug log.
John NeilanJohn Neilan
Thanks!  I fixed the 1st part of the problem as it was a recursive issue.  For the 2nd issue, I created a custom field on the Opp that was a text formula field to pull in the text of the Account name, and it works fine.  Kevin, I'm not sure how to query the Accounts separatel just to get the name.  Would I need to create a Map or something to link it to the existing Opportunity?  Thanks.
kevin lamkevin lam
Yes, creating a map is an option, another is use a formula field to store the account name.
This was selected as the best answer
John NeilanJohn Neilan
Thanks.  I ended up using a formula field to store the Account Name and it works.  Thanks for your help!