I have a trigger to make rejection comments mandatory. I have many records that have already been approved/rejected without comments. When a user attempts to reject a record that has already been approved or reject AND HAS NO comments, they receive an error (RequireRejectionComment: execution of BeforeUpdate caused by: System.ListException: List index out of bounds: 0: Trigger.RequireRejectionComment: line 29, column 1).
trigger RequireRejectionComment on carrier__c (before update) {
Map<Id, carrier__c> rejectedStatements = new Map<Id, carrier__c>{};
for(carrier__c car: trigger.new)
{
carrier__c oldcar = System.Trigger.oldMap.get(car.Id);
if (oldcar.Approval_Status__c != 'Rejected'
&& car.Approval_Status__c == 'Rejected')
{
rejectedStatements.put(car.Id, car);
}
}
for (ProcessInstance pi : [SELECT TargetObjectId,
(
SELECT Id, StepStatus, Comments
FROM Steps
WHERE StepStatus = 'Rejected'
ORDER BY CreatedDate DESC
LIMIT 1
)
FROM ProcessInstance
WHERE TargetObjectId In
:rejectedStatements.keySet()
ORDER BY CreatedDate DESC
])
{
***if ((pi.Steps[0].Comments == null || pi.Steps[0].Comments.trim().length() == 0))***
{
rejectedStatements.get(pi.TargetObjectId).addError(
'Please enter a rejection comment!');
}
}
}
Your guidance is much appreciated.
Best Answer
As far as I can see and understand your logic and code ar correct. The only thing I can think of is adding an additional condition to verify the list isn't empty.
but if we're not sure what data scenario does end up in your query, yet having no Step records, this could introduce a bug...