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

  • ,after given the comment also you are facing the same error? – Avijit Das Apr 25 '17 at 9:47
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()]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.