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
Geof131313Geof131313 

Automatically Approving

Hello,

I have what I thought would be a simple requirement, namely to automatically approve a record if the assigned approver is a specific user. Unfortunately, the Approval object does not allow for triggers, and I can't find any sample code anywhere to go off of. 

Thanks,

Geoffrey

Best Answer chosen by Admin (Salesforce Developers) 
Starz26Starz26

Where are you getting the approver from?

 

If it is a related user, can you set the criteria in the approval process that if the field is != that value put in the process else approve record?

 

Otherwise, you will have to write a trigger on the object that was actually submitted for approval

 

Here is some code I use in a test method to approve a record

 

//Approve the record
            ProcessInstance pi = [Select ID, Status, TargetObject.Name 
                From ProcessInstance 
                Where TargetObjectID = :IDOFRECORD AND Status = 'Pending'];

            if(pi !=Null){
                ProcessInstanceWorkitem piwi = [select Id,OriginalActorId from ProcessInstanceWorkitem where ProcessInstanceId= :pi.Id LIMIT 1];
                Approval.ProcessWorkitemRequest prWkItem = new Approval.ProcessWorkitemRequest();
                prWkItem.setWorkItemID(piwi.id);
                prWkItem.setComments('Auto Approve');
                prWkItem.setAction('Approve');
                Approval.ProcessResult appResult = Approval.process(prWkItem);
            }            

 

All Answers

Starz26Starz26

Where are you getting the approver from?

 

If it is a related user, can you set the criteria in the approval process that if the field is != that value put in the process else approve record?

 

Otherwise, you will have to write a trigger on the object that was actually submitted for approval

 

Here is some code I use in a test method to approve a record

 

//Approve the record
            ProcessInstance pi = [Select ID, Status, TargetObject.Name 
                From ProcessInstance 
                Where TargetObjectID = :IDOFRECORD AND Status = 'Pending'];

            if(pi !=Null){
                ProcessInstanceWorkitem piwi = [select Id,OriginalActorId from ProcessInstanceWorkitem where ProcessInstanceId= :pi.Id LIMIT 1];
                Approval.ProcessWorkitemRequest prWkItem = new Approval.ProcessWorkitemRequest();
                prWkItem.setWorkItemID(piwi.id);
                prWkItem.setComments('Auto Approve');
                prWkItem.setAction('Approve');
                Approval.ProcessResult appResult = Approval.process(prWkItem);
            }            

 

This was selected as the best answer