+ Start a Discussion

Aprroval through apex giving error

I am writing a trigger to approve a record submitted for approval using the standard 'Submit for approval' button. But when i do that the record is getting approved twice with the same date and time of approval. I was submitting the record for approval in the morning through apex and it was getting submitted twice. In the afternoon it was working fine, executing only one submission. This is happening with the same apex code without any modification. Can anyone please help me out? I am giving a sample for the code i have used below.

trigger triggerName on customObject (after insert, after update) { customObject cObj = Trigger.new[0]; ProcessInstance[] prInst = [Select Id from ProcessInstance where

                TargetObjectId=:cObj.Id and Status='Pending']; if(prInst.size()>0){

                ProcessInstanceWorkitem[] prInstWItem = [select Id,OriginalActorId from

                       ProcessInstanceWorkitem where ProcessInstanceId=rInst[0].Id]; Approval.ProcessWorkitemRequest prWkItem =

                                    new Approval.ProcessWorkitemRequest();


prWkItem.setComments('Approving request.'); prWkItem.setAction('Approve'); Approval.ProcessResult prResult = Approval.process(prWkItem);




Thanks in advance for your help.

I have found out why this is happening. I had written the code for approving the approval request in an after update trigger. Inside the trigger, I was again updating the same record. So the approval was happening in  a loop. I hope this is fixed now after Salesforce has rolled out an update to restrict the number of updates in a loop due to an update on the same record happening in an after update trigger. Anyways I have not tested that since I have changed my code.