Approval Process : How to Make Comment Mandatory of Approval Process in Salesforce ?

Approval Process :

In Order to understand the below code one must have some knowledge of Salesforce along with Approval Process and Apex. To learn all topics on Salesforce within 5 minutes click here.

Below is the code to make comment mandatory :

Source Code :

trigger casetriggerfinal on Case (before update) {
if(Trigger.isUpdate && Trigger.isBefore){
makecommentMandatory(trigger.new,trigger.oldmap);

}

public static void makecommentMandatory(List<Case> caseList,Map<Id,Case> oldcaseMap){
List<Id> caseId = new List<Id>();
for(Case c : caseList){
if(c.Approval_Status__c == ‘Approved’ && c.Approval_Status__c != oldcaseMap.get(c.Id).Approval_Status__c){
caseId.add(c.Id);
}
}

if(caseId.size() > 0){

List<ProcessInstance> piList = [Select Id,(Select Id, Comments from Steps) from ProcessInstance where TargetObjectId In : caseId];
for(case c : caseList){
for(ProcessInstance pi : piList){
for(ProcessInstanceStep piStep : pi.steps){
if(piStep.Comments == null || piStep.Comments == ”){
c.addError(‘Comment is Mandatory ‘);
}
}
}
}
}

}

}

You can also find the Same code at our YouTube Channel by clicking here

Now if we try to understand the code Line by Line: 

  1. trigger casetriggerfinal on Case (before update)

Above Trigger is in before Update because we have to add and Error and the Approval Process is going to update the record and hence the trigger is in Before Update Context

2. Use of next for Loop :
for(Case c : caseList){
if(c.Approval_Status__c == ‘Approved’ && c.Approval_Status__c != oldcaseMap.get(c.Id).Approval_Status__c){
caseId.add(c.Id);
}
}

Now the Above for loop is making sure that caseId list will be populated only when the Case is approved

3. Querying of Process Instance :

List<ProcessInstance> piList = [Select Id,(Select Id, Comments from Steps) from ProcessInstance where TargetObjectId In : caseId];

Now once the CaseId has value we are trying to query the process Instance based on that Case Id and getting the approval Process for that particular Case.

4. Using Loop to get the Process Instance and Steps along with Comments :

for(case c : caseList){
for(ProcessInstance pi : piList){
for(ProcessInstanceStep piStep : pi.steps){
if(piStep.Comments == null || piStep.Comments == ”){
c.addError(‘Comment is Mandatory ‘);
}
}
}
}

This is the Step where we are checking whether the Process instance steps has the comments as null and if they are null in that case we are adding error which will show a prompt on the screen.

 

Conclusion  : 

We Can Easily Manage the functionality of the Approval Process using Apex and also can manage the values and steps by querying the process instance.

Read More : GoPuff review 2023

Leave a Comment