0

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

0

1 Answer 1

0

You should filter steps by value "Rejected". As you are getting all steps with ProcessInstance object there can be steps without comments.

A query would be narrowed down to:

[SELECT TargetObjectId,
       (SELECT Id, StepStatus, Comments FROM Steps WHERE StepStatus='Rejected' ORDER BY CreatedDate DESC LIMIT 1 )
FROM ProcessInstance WHERE Id IN :processInstanceIds ORDER BY CreatedDate DESC]

You can even filter the ProcessInstance object by Status as:

[SELECT 
      (SELECT ID FROM ProcessInstances WHERE Status='Rejected' ORDER BY CreatedDate DESC LIMIT 1)
FROM TR_Currency_Approval__c WHERE ID IN :rejectedStatements.keySet()]
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .