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
Puja khetanPuja khetan 

cancel record which is in approval process

I have custome object on which i wanted to give Cancel   functionality to users .plan is to do using flow and apex .

on my custom object there is approval process as well .

my plan is 
if record status field value is New then simply i can change status to cancelled .

if record is submitted for approval ,in this case ,i am using lock check box ,which is checking if my recod is locked so in this case i have to call apex class that apex class need to delete this record queue from approval process queue .
as if simply i will change status to cancelled on this case as well then approval will still seeing this record is pending for their approval and they can approve .

so some one can help me apex code ? which simple will delete this record entry from approval queue ?
AnudeepAnudeep (Salesforce Developers) 
Here is a sample code to delete records from the approval process. Please make changes to your code as per your requirement
 
public class DeleteRecordsFromApprovalProcess
{
@InvocableMethod
public static void ApprovalProcessRecordsDelete(List OpportunityIds)
{
    List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest> ();

//Get Opps
Map<ID, Opportunity> opps : New Map<ID,Opportunity>([Select Id from Opportunity where ID IN:OpportunityIds]);

//Get ProcessInstance Items
Map<ID,ProcessInstance> piMap = New Map<ID,ProcessInstance>([Select Id from ProcessInstance where TargetObjectId IN :opps.keySet()]);


for(ProcessInstanceWorkItem pp : [Select Id from ProcessInstanceWorkItem where ProcessInstanceId IN :piMap.keySet()]){


// if there's a work item, set the action to 'removed' and execute
Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
req2.setAction('Removed');
req2.setWorkitemId(pp[0].Id);
requests.add(req2);
}

Approval.ProcessResult[] processResults = null;
processResults = Approval.process(requests, true);
}
}