+ Start a Discussion
GordymanLGGordymanLG 

Can a CaseComment trigger change a custom field in the associated Case?

I have a CaseComment trigger that fires when a new CaseComment is created by a Customer Portal user.  This trigger checks to see if the Case Status is Closed (using the IsClosed field).  If it is closed, I want to change the value of a custom field in the associated Case record from within the CaseComment trigger.

 

Is this possible and if so, how?

 

Here is my trigger code

 

trigger CloseComment on CaseComment (before insert) {
   Map<Id,CaseComment> cMap = new Map<Id,CaseComment>();
   for (CaseComment t: Trigger.new)

          {      cMap.put(t.ParentId,t);   }
   Set<Id> idSet = cMap.keySet();
   for(Case c:[select Id,IsClosed from Case where Id in :idSet]) {

      if(c.IsClosed) {

         c.NewCaseCommentonClosedCase__c = true;

 

        // here is where I want to commit this change to the associated Case record

 

     }

   }

}

 

 

Any help would be greatly appreciated.  If there is documentation on how to do this, a link to it would be just fine.

 

Thanks.

Ispita_NavatarIspita_Navatar

One cannot write trigger on CaseComment Object, so there is no CaseComment trigger, but here is how to figure out if a Case Comment  caused a Case trigger to fire without using workflow.The LastModifiedDate field of both the Case and CaseComment records are updated when a Case Comment is modified. However, when a Case record is modified, the LastModifiedDate of any associated CaseComment records are not modified. Consequently, you can compare the LastModifiedDate of the CaseComment records against the LastModifiedDate of the parent Case that generated
the trigger. If the LastModifiedDate of the Case record is newer than that of the child CaseComment, changes to the Case record caused the trigger. Otherwise, changes to the CaseComment caused the trigger.

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.

CaptainObviousCaptainObvious

You're close...

 

You don't actually want to "commit the change" within the for loop. Doing so may result in governor limit errors. Instead, put all the cases matching the criteria into a map. Once your loop is done, update that map with one DML statement:

 

 

trigger CloseComment on CaseComment (before insert) {
    Map<Id,CaseComment> cMap = new Map<Id,CaseComment>();
    for (CaseComment t: Trigger.new) {
        cMap.put(t.ParentId,t);   
    }
    Set<Id> idSet = cMap.keySet();
    Map<Id,Case> casesToUpdate = new Map<Id,Case>();

    for(Case c:[select Id,IsClosed from Case where Id in :idSet]) {
        if(c.IsClosed) {
            c.NewCaseCommentonClosedCase__c = true;
            casesToUpdate.put(c.id,c);
        }
    }
    if (casesToUpdate.size() > 0) {
        update casesToUpdate.values();
    }
}