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
Sarthak Bajaj 14Sarthak Bajaj 14 

Using Approval process in Trigger

Hi,

I have a requirement where I need to add validation rule(saying that a field is blank), but that validation should fire if in approval process the stage gets to in review/ or the approver is the Queue of the assigned approver.

I tried using validation rule, but it seems it is not achievable via validation rule.
It seems I need to write a trigger and use StepsAndWorkitems to get the actorId.

Can someone please guide me on how to achive this requirement?
 
Shiva RajendranShiva Rajendran
Hi Sarthak,
This is the trigger that creates approval process on account object
trigger AccountTriggerForAP on Account (after insert) {
         List<Account> abb = [select id,name from account where id in :acc];
           system.debug(abb);
     //  Account a=abb.get(0);
        User user1 = [SELECT Id FROM User WHERE email='varunrv1998@gmail.com'];
      //      List<Approval.ProcessSubmitRequest> allApprovalRequest=new List<Approval.ProcessSubmitRequest>();
       for(Account a:abb)
       {
        // Create an approval request for the account
        Approval.ProcessSubmitRequest req1 = 
            new Approval.ProcessSubmitRequest();
        req1.setComments('Submitting request for approval.');
        req1.setObjectId(a.id);
        
        // Submit on behalf of a specific submitter
        req1.setSubmitterId(user1.Id); 
        
        // Submit the record to specific process and skip the criteria evaluation
trigger AccountTriggerForAP on Account (after insert) {
         List<Account> abb = [select id,name from account where id in :acc];
           system.debug(abb);
     //  Account a=abb.get(0);
        User user1 = [SELECT Id FROM User WHERE email='varunrv1998@gmail.com'];
      //      List<Approval.ProcessSubmitRequest> allApprovalRequest=new List<Approval.ProcessSubmitRequest>();
       for(Account a:abb)
       {
        // Create an approval request for the account
        Approval.ProcessSubmitRequest req1 = 
            new Approval.ProcessSubmitRequest();
        req1.setComments('Submitting request for approval.');
        req1.setObjectId(a.id);
        
        // Submit on behalf of a specific submitter
        req1.setSubmitterId(user1.Id); 
        
        // Submit the record to specific process and skip the criteria evaluation
        req1.setProcessDefinitionNameOrId('ApprovalForAccount');
        req1.setSkipEntryCriteria(true);
 
        // Submit the approval request for the account
        Approval.ProcessResult result = Approval.process(req1);
        
        // Verify the result
        System.assert(result.isSuccess());
        
        System.assertEquals(
            'Pending', result.getInstanceStatus(), 
            'Instance Status'+result.getInstanceStatus());
              
// The below code is for auto approving the approval request
        // Approve the submitted request
        // First, get the ID of the newly created item
        List<Id> newWorkItemIds = result.getNewWorkitemIds();
        
        // Instantiate the new ProcessWorkitemRequest object and populate it
        Approval.ProcessWorkitemRequest req2 = 
            new Approval.ProcessWorkitemRequest();
        req2.setComments('Approving request.');
        req2.setAction('Approve');
        req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
        
        // Use the ID from the newly created item to specify the item to be worked
        req2.setWorkitemId(newWorkItemIds.get(0));
        
        // Submit the request for approval
        Approval.ProcessResult result2 =  Approval.process(req2);
        
        // Verify the results
        System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());
        
        System.assertEquals(
            'Approved', result2.getInstanceStatus(), 
            'Instance Status'+result2.getInstanceStatus());
       }
}        req1.setSkipEntryCriteria(true);
  
        // Submit the approval request for the account
        Approval.ProcessResult result = Approval.process(req1);
        
        // Verify the result
        System.assert(result.isSuccess());
        
        System.assertEquals(
            'Pending', result.getInstanceStatus(), 
            'Instance Status'+result.getInstanceStatus());
              
// The below code is for auto approving the approval request
        // Approve the submitted request
        // First, get the ID of the newly created item
        List<Id> newWorkItemIds = result.getNewWorkitemIds();
        
        // Instantiate the new ProcessWorkitemRequest object and populate it
        Approval.ProcessWorkitemRequest req2 = 
            new Approval.ProcessWorkitemRequest();
        req2.setComments('Approving request.');
        req2.setAction('Approve');
        req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
        
        // Use the ID from the newly created item to specify the item to be worked
        req2.setWorkitemId(newWorkItemIds.get(0));
        
        // Submit the request for approval
        Approval.ProcessResult result2 =  Approval.process(req2);
        
        // Verify the results
        System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());
        
        System.assertEquals(
            'Approved', result2.getInstanceStatus(), 
            'Instance Status'+result2.getInstanceStatus());
       }
}

I couldn't understand your last statement, by the way that can be handled by changing the codes in approval.processworkitemrequest req2.
Also before creating this class ,you have to setup approvalprocess on the object and use the same name in
        req1.setProcessDefinitionNameOrId('ApprovalForAccount');
Go through this for  setting up a approval creation
https://help.salesforce.com/articleView?id=approvals_creating_approval_processes.htm&language=en&type=0

Let me know if you need further help
Thanks and Regards,
Shiva RV
Sarthak Bajaj 14Sarthak Bajaj 14
Thanks for writing back Shiva.
Currently I have a custom object Requirement__c which is using the standard approval process..
Now the change that needs to be implemented is, I need to add three new picklist fields (which i have added).
Requiremnet is not everyone should get validation error while updating/creating a Requirement.But before the approval process changes the stage to implemented, business needs that the three fields shouldnever be kept black, so they came up with having a rule so that when in approval process stage is in development, then they should get error while approving the approval, so that at that point development team should fill those fields.

I tried using validation rule, but seems validation rule cannot be applied for the standard approval process.