0

Just wanted to know if the below Trigger can be further optimized. Requirement is to look for specific case record types with Approval and delete related case task that has got 'Credit Claim' in subject.

trigger DeleteRelatedTasks on Case (before insert, before update) {
    list<case> relatedCase = new list<case>();
    // Get the approved case record
    for (case myCase : Trigger.new) {
      if (myCase.VXRecordTypeName__c == 'Credit') {
        if (myCase.VXTL_Approval_Status__c == 'Approved' || myCase.VXTL_Approval_Status__c == 'Decline') {
                relatedCase.add(myCase);
        }
      }    
    // Delete related tasks
    string caseId = myCase.Id;
    list<Task> deleteTasks = [select whatid,Subject from Task where WhatId = :caseId];
    for (Task removeTasks : deleteTasks){
      if (removeTasks.Subject.contains('Credit Claim')) {
        delete deleteTasks;
      }     
    }
  }
}

1 Answer 1

7

Sure, there's lots of room for optimization.

First, don't use an insert event; it's absolutely impossible for a task to be attached to the case until after its created.

Second, don't put your DML operation or query inside a for loop.

Third, you can put your condition directly into your SOQL to pull only the records you want.

Fourth, you can combine the two if statements near the beginning in order to slightly reduce the complexity of your code.


trigger DeleteRelatedTasks on Case (after update) {
    list<case> relatedCase = new list<case>();
    // Get the approved case record
    for (case myCase : Trigger.new) {
      if (myCase.VXRecordTypeName__c == 'Credit' && 
          (myCase.VXTL_Approval_Status__c == 'Approved' || 
           myCase.VXTL_Approval_Status__c == 'Decline')) {
                relatedCase.add(myCase);
      }
    }
    if(!relatedCase.isEmpty()) {
      delete [SELECT Id FROM Task 
              WHERE WhatId = :relatedCase AND 
                    Subject LIKE '%CREDIT CLAIM%'];
    }
}

You must log in to answer this question.

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