+ Start a Discussion
Beer_Is_GodBeer_Is_God 

trigger Update_Opp_Amounts, therefore it cannot recursively update itself ----------help--------

Hi, I'm a newbe to Apex and am running into some issues with a trigger. The problem is that I am trying to update a list but I am receiving this error below

 

 

Error:Apex trigger Update_Opp_Amounts caused an unexpected exception, contact your administrator: Update_Opp_Amounts: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 006S0000003BqedIAC; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Update_Opp_Amounts: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 006S0000003BqedIAC; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 006S0000003Bqed) is currently in trigger Update_Opp_Amounts, therefore it cannot recursively update itself: [] Trigger.Update_Opp_Amounts: line 26, column 9: []: Trigger.Update_Opp_Amounts: line 26, column 9 

 

 

My code

 

 

trigger Update_Opp_Amounts on Opportunity (before insert, before update)
{
    List<Opportunity> Opp= Trigger.new;
    List<String> OppOwner =  new List<String>();
   
    for (Opportunity Oppy:Opp)
    {
        OppOwner.add(Oppy.OwnerID); 
    }
   
    List<Opportunity> OppAmounts = [SELECT Amount, Total_Pipe_Line__c FROM Opportunity WHERE
                        StageName not in('Closed Lost', 'Order Received') and ownerID IN :OppOwner]; 
   
    decimal total_amount = 0.0;
    decimal amounts = 0.0;
   
    for (Opportunity OppUpdate:Opp)
    {
        for (Opportunity OppAmnts:OppAmounts)
        {
            amounts = OppAmnts.Amount;
            total_amount += amounts;
            OppUpdate.Total_Pipe_Line__c = total_amount;
        }
        OppUpdate.Total_Pipe_Line__c = total_amount;

        Update OppAmounts    //problem here with the update
    }     
}

 

As my code suggests I would like to try and update ALL records in OppAmounts list and not just update on the current record. Does any one have any suggestions on how to do this please?

jgrenfelljgrenfell
You're hitting this error because you're updating a list (OppAmounts) that contains records that are in the Trigger.new collection that's being processed.  I think if you just move all of this logic to an "after insert, after update" trigger, it will work the way you want it to.