loading... Salesforce Cat
Showing posts with label Submit. Show all posts
Showing posts with label Submit. Show all posts

Wednesday, December 24, 2014

Controlling Approval Proccesses From Apex

Salesforce Approval Processes are one of the greatest declarative features comes with the platform.It saves tons of work you have to do as developer if you had to implement them via code.Although they are very useful in their default form, you may come up against requirements that require more than declarative customizations provide. Programmatic access to Salesforce Approval process via Apex come can handy in such situations. This Post discusses how Approval Process Submit ,Approve and Reject actions can be triggered from Apex code

Submit 



 Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();  
 req1.setComments('Submitting request for approval.');  
 req1.setObjectId(RecordId);  
 //RecordId is the id of the record that is submitted for Approval  
 Approval.ProcessResult result = Approval.process(req1);                                    


Approve


 //RecordId is the id of the record that is submitted for Approval 
List<ProcessInstance> PI = [Select Id,TargetObjectId FROM ProcessInstance WHERE TargetObjectId=:RecordId AND Status='Pending'];  
 if(PI.size() > 0)  
 {  
  List<ProcessInstanceWorkitem> PIWI = [Select Id ,ActorId FROM ProcessInstanceWorkitem WHERE ProcessInstanceId=:PI[0].Id];  
  if(PIWI.size() > 0)  
  {  
   Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();  
   req2.setComments('Approving request.');  
   req2.setAction('Approve');  
   req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});  
   req2.setWorkitemId(PIWI[0].Id);  
   Approval.ProcessResult result2 = Approval.process(req2);  
  }  
 }  


Reject



 //RecordId is the id of the record that is submitted for Approval 
List<ProcessInstance> PI = [Select Id,TargetObjectId FROM ProcessInstance WHERE TargetObjectId=:RecordId AND Status='Pending'];  
 if(PI.size() > 0)  
 {  
      List<ProcessInstanceWorkitem> PIWI = [Select Id ,ActorId FROM ProcessInstanceWorkitem WHERE ProcessInstanceId=:PI[0].Id];  
     if(PIWI.size() > 0)  
     {  
          Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();  
         req2.setComments('Approving request.');  
         req2.setAction('Reject');  
         req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});  
         req2.setWorkitemId(PIWI[0].Id);  
         Approval.ProcessResult result2 = Approval.process(req2);  
     }  
 }