How to Add @mention to Chatter Post through Apex where Process Builder Not works

Use Case: This is mostly helpful when you are re-assigning any records and want to notify new owner . After re-assigning you will loose the access to the record when OWD is set to Private and you can't post chatter / notify new owner through process builder.

To achieve this you have to write before trigger on the respective object Record where you want to post the feed.

In this case I am taking Case record where OWD is set to private.

Trigger:
=================
trigger PostChatterFeed on Case (before insert , before update) {

List<FeedItem> fi = new List<FeedItem>();
User us= [select Id,Name from User where Id = :trigger.new[0].OwnerId];
for(case c :trigger.new){

if(c.OwnerId != trigger.old[0].OwnerId){


//This way @mention will be a normal text

/*  String status = +'@'+us.Name + ' Member Request Case Number ' + c.CaseNumber+ 'has been assigned to you.!';
  FeedItem post = new FeedItem(
            ParentId = c.Id,
          //  Title = opp.Name,
            Body = status
        );
        fi.add(post);
        }
    }
    insert fi;*/

//Use this Method to @mention
MentionsUtility.mentionedUser(trigger.new[0]);
}
    }
}


Class:
========================
public with sharing class MentionsUtility { 

    public static void mentionedUser(Case cs){          
       
    //    Case c = [ Select OwnerId From Case Where Id =: caseRecordId];

        ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
        ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
        ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
        ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

        messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

        mentionSegmentInput.id = cs.OwnerId;
        messageBodyInput.messageSegments.add(mentionSegmentInput);

        textSegmentInput.text = +' '+'Member Request Case Number'+' '+cs.CaseNumber+' '+'has been assigned to you.';
        messageBodyInput.messageSegments.add(textSegmentInput);

        feedItemInput.body = messageBodyInput ;
        feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
        feedItemInput.subjectId = cs.Id;

        ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput, null);
    }
}


You can use this method where ever you want with slight modifications.




Post a Comment

0 Comments