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
TsvetyTsvety 

Automatic rejection for records in an approval process

Hi experts,

I have a custom object Submittals and an approval process built for it.

The use case is:
A record was submitted and is pending approval
If a field ("status") on the Submittal is changed to "closed" all pending submittals should be automatically rejected.

How to accomplish this?

Thank you!
CodeITCodeIT
I think you can add a trigger on this object, once status is set to "Closed", fire following code (below code only handles one record) and make sure the approvers are set up properly:
/*Code generated by ForceXtra.com */
public boolean Reject(string CaseId){
	ProcessInstanceWorkItem piwi= GetWorkItem(caseid);	
	if(piwi!=null)
	{
		Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
		req.setAction('Reject');
		req.setWorkitemId(piwi.id);
		Approval.ProcessResult result = Approval.process(req);
		return result.isSuccess();
	}
	return false;
}

public ProcessInstanceWorkItem GetWorkItem(string caseId)
{
	Case cases = [
	    select  Id,
	            (select ProcessInstanceId, IsPending  from ProcessSteps order by CreatedDate) 
	    from Case c 
	    where Id =: caseId 
	];
	
	string ProcessInstanceId;
	if (cases.ProcessSteps.size() == 0) {
	    return null;
	}
	// make sure the Case has submitted for approval
	for (ProcessInstanceHistory pih : cases.ProcessSteps) {
	    if(pih.IsPending) {
	        ProcessInstanceId = pih.ProcessInstanceId;
	    }
	}
	
	if (ProcessInstanceId==null)return null;
	
	ProcessInstanceWorkItem[] workitem = [select Id, ActorId from ProcessInstanceWorkItem where ProcessInstanceId = : ProcessInstanceId ];
	return (workitem.size() == 0 ? null : workitem[0]);
}

 
TsvetyTsvety
Thank you for taking the time to reply. In almost all cases, there will be more than 1 item pending approval. 
CodeITCodeIT
then you need to change above code to process multiple records in the trigger