I need to make Approval rejection comments mandatory, to do that i am using a trigger suggsted by Mr. Christopher , that was working fine if the user does not given the comments, but the issue is trigger is firing when the user has given the comments, posting my code here
trigger TR_Reject_Approval_Comments on TR_Currency_Approval__c(before update)
{
Map<Id, TR_Currency_Approval__c> rejectedStatements = new Map<Id, TR_Currency_Approval__c>{};
for(TR_Currency_Approval__c cur: trigger.new)
{
TR_Currency_Approval__c oldCur = System.Trigger.oldMap.get(cur.Id);
if (oldCur.Approval_Status__c != 'Rejected' && cur.Approval_Status__c == 'Rejected')
{
rejectedStatements.put(cur.Id, cur);
}
}
if (!rejectedStatements.isEmpty())
{
List<Id> processInstanceIds = new List<Id>{};
for (TR_Currency_Approval__c curn : [SELECT
(SELECT ID FROM ProcessInstances ORDER BY CreatedDate DESC LIMIT 1)
FROM TR_Currency_Approval__c WHERE ID IN :rejectedStatements.keySet()])
{
processInstanceIds.add(curn.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[0].Comments == null ||
pi.Steps[0].Comments.trim().length() == 0))
{
rejectedStatements.get(pi.TargetObjectId).addError('Please provide a rejection reason!');
}
}
}
}
Please let me know if i am doing any mistake,or suggest me any other ways to do this