Required to Fill Comment Before Approved/Rejected Using Apex Code
Requirement: When User Approved or Rejected the approval then it is required to fill Approval
or Rejected reason
Solution : You need to write the the trigger on Before Update as mention below
private void ApprovedOrRejectedComment(list<Sobject> triggerNew, map<id,Sobject> triggerOldMap)
{
Map<Id, Sobject> MapIDToObject = new Map<Id, Sobject>{};
for(Sobject objSobj: triggerNew)
{
Sobject oldobjSobj = triggerOldMap.get(objSobj.Id);
if (((oldobjSobj.Status != 'Approved'
&& objSobj.Status == 'Approved' )
||(oldobjSobj.Status != 'Rejected'
&& objSobj.Status == 'Rejected')))
{
MapIDToObject.put(objSobj.Id, objSobj);
}
}
if (!MapIDToObject.isEmpty())
{
List<Id> processInstanceIds = new List<Id>();
for (Sobject objSobjs : [SELECT (SELECT ID FROM ProcessInstances
ORDER BY
CreatedDate DESC
LIMIT 1)
FROM Sobject
WHERE ID IN:MapIDToObject.keySet()])
{
processInstanceIds.add(objSobjs.ProcessInstances[0].Id);
}
for (ProcessInstance pi : [SELECT TargetObjectId,
(SELECT Id, StepStatus, Comments
FROM Steps
ORDER BY CreatedDate DESC
LIMIT 1 )
FROM ProcessInstance
WHERE Id IN :processInstanceIds
ORDER BY CreatedDate DESC])
{
if(pi.Steps.size()>0)
{
if ((pi.Steps[0].Comments == null
|| pi.Steps[0].Comments.trim().length() == 0))
{
MapIDToObject.get(pi.TargetObjectId).addError(
Please Provide a Approved/Rejected Reason. It should not be blank !');
}
}
}
}
}
Note: "Approved/Rejected " will work when you added field updated in Final Approval/Final Rejection while creating the Approval process
Comments
Post a Comment