function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Admin one 7Admin one 7 

When case is closed, how to create case comment ??

Hi all,

When I am closing the case, I want to create case comment for that particular case, when I am editing the same closed case I don’t want to create another case comment.

So, can you help me out to write trigger for this.
 
Bhanu MaheshBhanu Mahesh
Hi,

Please try below code
 
trigger CreateCommentOnClose on Case (after update) {
    
    List<CaseComment> lstCommentsToInsert = new List<CaseComment>();
    //Iterate over the cases that are being updated
    for(Case cas : trigger.new){
        if(cas.Status == 'Closed' && trigger.oldMap.get(cas.Id).Status != 'Closed'){
            
            CaseComment comment = new CaseComment();
            comment.ParentId = cas.Id;
            comment.CommentBody = 'Case is Clsoed';
            lstCommentsToInsert.add(comment);
        }
    }
    //Insert Case Comments
    if(!lstCommentsToInsert.isEmpty()){
        insert lstCommentsToInsert;
    }
}

Mark this as "SOLVED" if your query is answered

Thanks,
Bhanu Mahesh
UC InnovationUC Innovation
Give this a try.  This should also take care of the situation where someone marked the case as Closed when creating a case:
 
// Need after insert to get the Case ID to assign to the CaseComment's ParentId field.
// Before insert won't have the Case ID yet.
trigger CaseTrigger on Case (after insert, before update) {

    List<CaseComment> caseCommentList = new List<CaseComment>();
    
    for (Integer i = 0; i < Trigger.New.Size(); i++) {
        Case oldCase = null;
        
        // Before insert won't have Trigger.Old
        if (Trigger.Old != null) {
        	oldCase = Trigger.Old[i];
        }
        
        Case newCase = Trigger.New[i];
        
        if (oldCase == null && newCase.Status == 'Closed' ||
            oldCase != null && oldCase.Status != 'Closed' && newCase.Status == 'Closed') {
            
            CaseComment comment = new CaseComment();
            comment.ParentId = newCase.Id;
            comment.CommentBody = 'Some comment body';
            caseCommentList.Add(comment);
        }
    }
    
    insert caseCommentList;
}

 
UC InnovationUC Innovation
Admin one, did one of these solutions work for you?