+ Start a Discussion
Doug ACFDoug ACF 

Updating Original Record in After Insert Trigger

I am writing a trigger to copy an auto-number field into another text field whenever an opportunity is created.  I'm using an "after insert" since I don't think an auto-number value is available in a "before insert".  The update executes successfully, but no data is actually populated in the record.  When I run the exact same code with an "after update", it works fine.  What am I missing here about "after insert"?

Code:
trigger CopyOptyID on Opportunity (after insert) {

// Only execute trigger if context variable indicates it has not executed already

if (!TriggerHelper.hasAlreadyCopiedOptyID()) 
{

// Initialize array to hold Opportunity records to be updated

 Opportunity[] newOpps = new Opportunity[]{};

// Loop through each Opportunity triggered and if type="New", copy Opty_ID to Original_Opty_ID

 for (Opportunity opps:Trigger.New) {

  if (opps.Type=='New')
  {
   Opportunity o = new Opportunity(Id=opps.Id);
   o.Original_Opty_ID__c=opps.Opty_ID__c;
   newOpps.add(o);
  }
 }

// Set context variable to indicate that trigger has already executed

 TriggerHelper.setAlreadyCopiedOptyID();

// Update Opportunity records

 try {
  System.debug(newOpps);
  update newOpps;
 } catch (DmlException e) {
   System.debug(e.getMessage());
 }

}

}