Insert new case comment using Apex Trigger in salesforce

Task: I need to insert the CaseComment to all the Relevant Cases whenever New casecommnet is created or updated Using Trigger,


trigger updateCaseComment on CaseComment(after insert, after update) {
Map<Id,CaseComment> caseMap = new Map<Id,CaseComment>();
for (CaseComment t: Trigger.new){
caseMap.put(t.ParentId,t);
}

Set<Id> idSet = caseMap.keySet();
List<Case> allCases = [select Id,ParentId from Case where ParentId in :idSet];
List<CaseComment> childCommand = new List<CaseComment>();
for(integer i=0;i<allCases.size();i++){

CaseComment newCommmand = new CaseComment();
newCommmand.CommentBody = caseMap.get(allCases[i].ParentId).CommentBody;
newCommmand.IsPublished = TRUE;
newCommmand.ParentId = allCases[i].id;
childCommand.add(newCommmand);
}

if(!childCommand.isEmpty()){
insert childCommand;
}
}

Written by 

Salesforce MVP | Lightning Champion | 16x Salesforce Certified | Application Architect | 6x Trailhead Ranger | Techforce Services | Australia

Leave a Reply

Your email address will not be published. Required fields are marked *

*