I've put together some code to automate the completion of CaseMilestones when the user makes certain changes to a Case.
trigger completeCaseMilestone on Case (after update) {
List<WEID__c> weids = WEID__c.getall().values();
Set<Id> validRecordTypeIds = new Set<Id>();
// add Case Record Type Ids from Custom Setting to list of valid Ids
for (WEID__c weid: weids) {
try {
validRecordTypeIds.add(weid.WECaseId__c);
} catch (System.StringException e) {
System.debug(
System.LoggingLevel.ERROR,
'Invalid Record Type Id ' + weid.WECaseId__c
);
}
}
// create a list of Cases with valid Record Types
List<Case> caseIds = new List<Case>();
for (Case c : Trigger.new){
if(validRecordTypeIds.contains(c.RecordTypeId))
{
caseIds.add(c);
}
}
if(caseIds.isEmpty() == true){
system.debug('No Cases with both a valid Record Type Id were found');
// exit trigger if no Cases with valid Record Type Ids are found
return;
}
else{
List<Id> acceptedIds = new List <Id>();
for (Case c1 : caseIds){
Case oldCase1 = Trigger.OldMap.get(c1.Id);
if(oldCase1 != null && oldCase1.OwnerId != c1.OwnerId)
{
acceptedIds.add(c1.Id);
System.debug('acceptedIds size is ' + acceptedIds.size());
}
if(acceptedIds.isEmpty() == true){
System.debug('No Cases with new owners were found');}
else{
List<Id> closedIds = new List <Id>();
for (Case c2 : caseIds){
Case oldCase2 = Trigger.OldMap.get(c2.Id);
if(oldCase2.IsClosed == false && c2.IsClosed == true)
{
closedIds.add(c2.Id);
System.debug('closedIds size is ' + closedIds.size());
}
if(closedIds.isEmpty() == true){
system.debug('No newly closed Cases were found');}
The below section isn't working as expected
List<Id> closedIds = new List <Id>();
for (Case c2 : caseIds){
Case oldCase2 = Trigger.OldMap.get(c2.Id);
if(oldCase2.IsClosed == false && c2.IsClosed == true)
{
closedIds.add(c2.Id);
System.debug('closedIds size is ' + closedIds.size());
}
if(closedIds.isEmpty() == true){
system.debug('No newly closed Cases were found');}
Whereas both system debug messages are 'printed' depending on whether the criteria has been met or not for the acceptedIds section, the closedIds debug only works when the list is empty.
When the Case has been closed - the Date/Time Closed field is being populated - the debug message stating the size of that list isn't printed (and neither is the message stating that 'no newly closed Cases were found').