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
Cris9931Cris9931 

Self Reference from Trigger

Hi all,

I have the following error:

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


This is my trigger:

trigger countWL on SVMXC__Parts_Request_Line__c (before update, before insert) {


     //take all the parts line with their parts work detail
     List<SVMXC__Parts_Request_Line__c> partsWithWL = [SELECT Id,Name,(SELECT Id,Name FROM Work_Details__r WHERE SVMXC__Line_Type__c= 'Parts') FROM SVMXC__Parts_Request_Line__c WHERE Id IN :Trigger.New];
     System.debug('partsWithWL '+partsWithWL);
     
    
     for(SVMXC__Parts_Request_Line__c loopParts : partsWithWL ){
         loopParts.CountWLParts__c = loopParts.Work_Details__r.size();
         update loopParts;
         System.debug('loopParts.CountWLParts__c' + ' '+loopParts.CountWLParts__c);
        
     }
   
   
}

What I am doing wrong here? Why the trigger fails?​​​​​​​
vishal-negandhivishal-negandhi

Hi Cristian, 

 

What you're doing wrong is the below statement:
update loopParts;

Your trigger executes on before update and before insert operations and when we use these events, we don't need to perform explicit updates. 

You just need to remove that statement and your trigger will run fine. 

 

If you pay attention to the error message, it tells you that you're trying to update a record which is already in trigger context. 

Hope this helps.

 

On a side note, you can remove "before insert" as well, since you'll never have related data for the insert operation. 

 

Best,

Vishal