+ Start a Discussion
Mike SimmenMike Simmen 

trigger to recall an approval process when custom object field is updated

Hello,

I am having issues getting the workitemid.  Please help.  I am trying to recall an approval process whenever a user cancels the request from the object.  Here is my code.
 
trigger FlightRequestRecallwhencancelled on Demo_Request__c (after update)
{

    for (Integer i = 0; i < Trigger.new.size(); i++)
    {
     try
     {
        if(Trigger.old[i].Cancel_this_Request__c != Trigger.new[i].Cancel_this_Request__c)
        {
           recallRecord(Trigger.new[i]);
        }
     }catch(Exception e)
     {
         Trigger.new[i].addError(e.getMessage());
     }
    }
    
    /**
    * Get ProcessInstanceWorkItemId using SOQL
    **/
    public Id getWorkItemId(Id targetObjectId)
    {
        Id retVal = null;

        for(ProcessInstanceWorkitem workItem  : [Select p.Id from ProcessInstanceWorkitem p
            where p.ProcessInstance.TargetObjectId =: targetObjectId])
        {
            retVal  =  workItem.Id;
        }

        return retVal;
    }

    /**
    * This method will Recall the Flight Request Approval
    **/
    public void recallRecord(Demo_Request__c d)
    {
        Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
        req.setComments('Approval Recalled due to Flight Request Cancellation');
        req.setAction('Removed');
        Id workItemId = getWorkItemId(d.id); 

        if(workItemId == null)
        {
            d.addError('Recall Approval Error');
        }
        else
        {
            req.setWorkitemId(workItemId);
            // Submit the request for approval
            Approval.ProcessResult result =  Approval.process(req);
        }
    }
}

 
ShashankShashank (Salesforce Developers) 
Is there an error you are seeing when you try to use it? That should give some clues.