Trigger Handler Class & Trigger on After Update:
private void postChatterupdatecase(ClsWrappers.TriggerContext trgCtx) {
if (trgCtx.isAfter && trgCtx.isUpdate){
Set<Id> ownerManagerIdSet = new Set<Id>();
Map<Id,Case> oldCaseMap = new Map<Id,Case>();
for(sobject so : trgCtx.oldList){
Case csOld = (Case)so;
oldCaseMap.put(csOld.Id,csOld);
}
for(sobject so : trgCtx.newList){
Case cs = (Case)so;
ownerManagerIdSet.add(cs.OwnerId);
}
Map<id,User> user_map = new Map<id, User>(
[select Id,isActive,manager.Id from User where isActive = true AND Id IN: ownerManagerIdSet LIMIT 5000]);
System.debug('*********** user_map *' + user_map);
for(sobject so : trgCtx.newList){
Case cs = (Case)so;
if (cs.Milestone_message__c != oldCaseMap.get(cs.Id).Milestone_message__c && user_map.containsKey(cs.Ownerid)){
if(cs.Is_Violation_Action__c == true && cs.Milestone_message__c != null){
if(user_map.get(cs.OwnerId).manager.Id != null){
CreateChatterFeed.ChatterAPI(cs.Milestone_message__c, new List<Id> {user_map.get(cs.OwnerId).manager.Id, cs.OwnerId}, cs.Id);
// cs.Milestone_message__c = null;
}
else{
CreateChatterFeed.ChatterAPI(cs.Milestone_message__c, new List<Id> {cs.OwnerId}, cs.Id);
}
}
if(cs.Is_Violation_Action__c == false && cs.Milestone_message__c != null){
CreateChatterFeed.ChatterAPI(cs.Milestone_message__c, new List<Id> {cs.OwnerId}, cs.Id);
}
}
}
}
}
// Chatter posting API
public without sharing class CreateChatterFeed {
public static void ChatterAPI(String messageToPost, List<id> usersToPost, id objectToPost){
ConnectApi.FeedItemInput feedItemInput_1 = new ConnectApi.FeedItemInput();
String delimitor = ', ';
ConnectApi.MessageBodyInput messageBodyInput_1 = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput_1 = new ConnectApi.TextSegmentInput();
ConnectApi.TextSegmentInput delimitorInput = new ConnectApi.TextSegmentInput();
delimitorInput.text = delimitor;
messageBodyInput_1.messageSegments = new List<ConnectApi.MessageSegmentInput>();
for (id userToMention : usersToPost){
ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
mentionSegmentInput.id = userToMention;
messageBodyInput_1.messageSegments.add(mentionSegmentInput);
messageBodyInput_1.messageSegments.add(delimitorInput);
}
textSegmentInput_1.text = messageToPost;
messageBodyInput_1.messageSegments.add(textSegmentInput_1);
feedItemInput_1.body = messageBodyInput_1;
feedItemInput_1.feedElementType = ConnectApi.FeedElementType.FeedItem;
feedItemInput_1.subjectId = objectToPost;
if(!Test.isRunningTest()){
ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput_1);
}
}
}
Output:
select
id, whatid
from
task
where
what.type
=
'Case'