Mention multiple users in the chatter post using Apex

In this post, I am going to share how we can post the chatter from Apex code and mention the multiple users in the post.

Scenario: If the Account owner is changed, post a chatter and mention the “Account Reviewer “profile users based on old and new owner regions. Account Reviewer from the old and new owner regions should get notification of this change.

Solution: Create an Apex Trigger on the Account object and a trigger helper class. Use ConnectApi to create the feed item and mention the users in the post.

AccountTrigger.apxt

trigger AccountTrigger on Account (after update) {
    
    if(Trigger.isAfter && Trigger.isUpdate){
        list<Account> newAccountList = new List<Account>();
        for(Account acc: Trigger.new){
            if( Trigger.oldMap.get( acc.id ).ownerId != Trigger.newMap.get( acc.id ).ownerId ){
                newAccountList.add(acc);
            }
        }
        if(newAccountList.size()>0)
            AccountTriggerHelper.postChatterOnOwnerChange(Trigger.oldMap, Trigger.newMap,Trigger.new);
    }
}

AccountTriggerHelper.apxc

public with sharing class AccountTriggerHelper {
	//Post chatter on owner of Account gets changes and mention the Account reviewer users in the chatter based on old and new onwer region
    public static void postChatterOnOwnerChange(Map<Id,Account> oldAccounts, Map<Id,Account> newAccounts,List<Account> accList){
        //set to store the account owner Ids
        set<Id> newOwnerIds = new set<Id>();
        set<Id> oldOwnerIds = new set<Id>();
        
        //put account owner ids in set
        for(Account acc: accList){newOwnerIds.add(acc.ownerId);}
        // Map will store the account owner informations
        Map<Id,user> newOwnerMap = new Map<Id,user>([select id,Name,Region__c from user where id IN:newOwnerIds]);
        
        for(Account acct: oldAccounts.values()){oldOwnerIds.add(acct.ownerId);}
        Map<Id,user> oldOwnerMap = new Map<Id,user>([select Id,Name,Region__c from user where id IN:oldOwnerIds]);
        
        //This map will store the user region as key and list of account reviewer as value
        Map<String,List<User>> accountReviewerUsersMap = new Map<String,List<User>>();
        
        //iterate over users where profile = Account Reviewer and isActive = TURE
        for(User u:[select id,Region__c from user where Profile.Name='Account Reviewer' and isActive = true]){
            //get the list of account reviewer user from map
            List<User> userList = accountReviewerUsersMap.get(u.Region__c);
            if (userList == null) { // If List is null then put the value in the map
                userList = new List<User>();
                accountReviewerUsersMap.put(u.Region__c, userList); //put the region as key and list of user as value in the map
            }    
            //add the users in the list
            userList.add(u);
            
        }
        
        for(Account acc: accList){
            List<User> oldOwnerAccountReviewer = new List<User>();
            List<User> newOwnerAccountReviewer = new List<User>();
            //new owner account reviewer
            User newAccOwner = newOwnerMap.get(acc.OwnerId);
            if(accountReviewerUsersMap.containskey(newAccOwner.Region__c))
                newOwnerAccountReviewer = accountReviewerUsersMap.get(newAccOwner.Region__c);
            
            //old owner account reviewer
            User OldaAccOwner = oldOwnerMap.get(oldAccounts.get(acc.Id).ownerId);
            
            if(accountReviewerUsersMap.containskey(OldaAccOwner.Region__c))
                oldOwnerAccountReviewer = accountReviewerUsersMap.get(OldaAccOwner.Region__c);
            
            List<User> owners = new List<User>();
            owners.addAll(newOwnerAccountReviewer);
            owners.addAll(oldOwnerAccountReviewer);

            ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
            ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
            ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
            
            messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
            
            // post body
            String postBody = '\'Account Owner\' has been changed field has been updated'+'\n\n';
            postBody += oldOwnerMap.get(oldAccounts.get( acc.id ).ownerId).Name + ' to '+ newOwnerMap.get(newAccounts.get( acc.id ).ownerId).Name + '\r\n\n';
            
            textSegmentInput.text = postBody;
            messageBodyInput.messageSegments.add(textSegmentInput);
            feedItemInput.body = messageBodyInput;
            
           
            //mention account reviewer from old and new onwer region
            for(user u: owners){
                ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
                mentionSegmentInput.id = u.Id;
                messageBodyInput.messageSegments.add(mentionSegmentInput);
            }
            
            
            feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
            //post on Account record
            feedItemInput.subjectId = acc.id;
            //post the chatter
            ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);  
        }
    }
}

Using this class (ConnectApi.MentionSegmentInput) you can mention the user or group in the feed post or in the comments. We can include up to 25 users/groups in the mention.

ConnectApi.MentionSegmentInput 

In this scenario, I have created/initialized the ConnectApi.MentionSegmentInput object in for loop so that multiple users can be mentioned in the chatter post.

//mention account reviewer from old & new owner region
 for(user u: owners){
          ConnectApi.MentionSegmentInput mentionSegmentInput = new 
                ConnectApi.MentionSegmentInput();
          mentionSegmentInput.id = u.Id;
          messageBodyInput.messageSegments.add(mentionSegmentInput);
 }

Result: Update the Account owner and chatter will be posted on the Account record. You can see all the mentioned users will be from the new & old owner region who has the “Account Reviewer” profile.

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

Leave a Reply