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
Ankit Garg 117Ankit Garg 117 

Trigger to post Task comments to Chatter

Hi, I am very new to the trigger and have very less experience with them.

I want to auto-populate the Comments on Task onto the Chatter. Is this possible via trigger? If yes, can someone please help me with thew trigger. Will be really thankful.

Thanks 
Best Answer chosen by Ankit Garg 117
ANUTEJANUTEJ (Salesforce Developers) 
I was able to use the below snippet and test class and 100 percent was covered in my org please do the necessary adjustments as it is a sample snippet.
trigger TaskChatter on Task (before insert)
{
    if(trigger.isbefore && (trigger.isinsert))
    {
        list<FeedItem> listfeed= new list<FeedItem>();
        for(task t:trigger.new)
        {
            if(t.description.contains('Check in Complete')){
                FeedItem post = new FeedItem();
                post.ParentId=t.WhatId;
                post.Body = t.Description;
                listfeed.add(post);}
        }
        if(listfeed.size()>0)
        {
            insert listfeed;
        }}
}
@isTest
public class TaskChatterTest {
    public static testmethod void insertTask() {
        Account a= new Account();
        a.Name='TestAccount';
        insert a;
    
        Task t = new Task();
        t.WhatId= a.Id ;
        t.Description ='Check in Complete';
        insert t; 
    
    FeedItem post = new FeedItem();
    post.ParentId=t.WhatId;
    post.Body = t.Description;
    insert post;
        String pbody= post.Body;

	System.assertEquals('Check in Complete',pbody,'Check Test Class');   
}
}

Please close the thread by marking this as the best answer so that it can be useful to others in the future.

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
Hi Ankit,

>> https://salesforce.stackexchange.com/questions/49591/create-chatter-post-and-mention-user-in-trigger

The above link has an example of creating a chatter post with @mention when task record is inserted can you try checking it once?

I am attaching the answer mentioned for quick reference:
 
public static void mentionTextPost(Id userId, Id userToMentionId, String postText) { 

   ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
   messageInput.messageSegments = new List();

   // add some text before the mention
   ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
   textSegment.text = 'Hey ';
   messageInput.messageSegments.add(textSegment);

   // add the mention
   ConnectApi.MentionSegmentInput mentionSegment = new ConnectApi.MentionSegmentInput();
   mentionSegment.id = userToMentionId;
   messageInput.messageSegments.add(mentionSegment);

   // add the text that was passed
   textSegment = new ConnectApi.TextSegmentInput();
   textSegment.text = postText;
   messageInput.messageSegments.add(textSegment);

   ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();
   input.body = messageInput;

   // post it
   ConnectApi.ChatterFeeds.postFeedItem(null, ConnectApi.FeedType.UserProfile, userId, input, null);

}

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
Ankit Garg 117Ankit Garg 117
Ji ANUTEJ, Thanks for the response. This is very confusing for me sorry. ☹ Can you please help me writing a trigger. I would be really greatful. Ankit Garg Salesforce Administrator [HealthShare] Level 6, 1 Newland St Bondi Junction, NSW 2022 Australia healthsharedigital.com [Deloitte Technology Fast 50 2018]
ANUTEJANUTEJ (Salesforce Developers) 
So, I wrote a sample snippet below:
 
trigger TaskChatter on Task (after insert, after update)
{
if(trigger.isafter && (trigger.isinsert|| trigger.isupdate))
{
list<FeedItem> listfeed= new list<FeedItem>();
for(task t:trigger.new)
{
FeedItem post = new FeedItem();
    post.ParentId=t.WhatId;
post.Body = t.Description;
listfeed.add(post);
}
if(listfeed.size()>0)
{
	insert listfeed;
}}
}

Please do note that this is a sample snippet and you need to modify it for your implementation.

Please close the thread by marking this as the best answer so that it can be useful to others in the future.

Thanks.
Ankit Garg 117Ankit Garg 117
Hi Anutej, 

Thanks a lot man. I have copied the trigger as is (only changed  (after insert, after update) to before update on the top line ) and trigger worked fine on sandbox. However, I may need a test class for the same :( can you please help me. Also, please also guide me how I can then deploy this in Production. 

Appriciate all your help thus far. Really do :)
Ankit Garg 117Ankit Garg 117
Also sorry, just got requirement updated. Can we do this only for the specific tasks? For example, I want this functionality only for those tasks only where the Task Subject is ''Check in Complete". 
ANUTEJANUTEJ (Salesforce Developers) 
As stated earlier this is just a sample code and you need to modify it to your use case, please try writing a sample test class and then in case if you face any issues you can share to get response.
Ankit Garg 117Ankit Garg 117
Thanks Anutej,

Here is what i have written but it is showing some errors. 

@isTest

public class TestClassForTaskTrigger {
    @isTest static void insertFeedItem() {
        FeedItem post = new FeedItem();
        post.ParentId = t.WhatId;
        post.Body = t.Description;
        listfeed.add(post);      
    }

}



User-added image
ANUTEJANUTEJ (Salesforce Developers) 
Before inserting FeedItem record you need to insert task t with whatId.

EDIT: Do notice whatId holds the reference to the id of any of these object record accounts, opportunities, campaigns, cases, or custom objects, so first you would be inserting the above object record then a task record that has the whatId and then you need to insert the FeedItem record. Followed by system,assert statement.
Ankit Garg 117Ankit Garg 117
Have gave it a go but still pondering over haha

@isTest

public class TestClassForTaskTrigger {
    @isTest static void insertTask() {
        Task t = new Task();
        t.Id = t.WhatId ;
        t.Description = t.Description;
        insert t;      
    }
list<FeedItem> listfeed= new list<FeedItem>();
{
    FeedItem post = new FeedItem();
    post.ParentId=t.WhatId;
    post.Body = t.Description;
listfeed.add(post);
    
}
}


User-added image
ANUTEJANUTEJ (Salesforce Developers) 
can you try something like the below:
 
@isTest

public class TestClassForTaskTrigger {
    @isTest
public static void insertTask() {
Account a= new Account();
a.Name="TestAccount";
insert a;
        Task t = new Task();
        t.WhatId= a.Id ;
        t.Description ='TestDescription';
        insert t;      
    FeedItem post = new FeedItem();
    post.ParentId=t.WhatId;
    post.Body = t.Description;
insert post;

System.assert('TestDescription',post.body);   
}
}

I see there are multiple corrections and to understand the basics you can check the below trailhead module to learn about testing in apex: https://trailhead.salesforce.com/en/content/learn/modules/apex_testing
Ankit Garg 117Ankit Garg 117
Thanks Anutej,

I will definately go through the module. This is what is coming up. Also, can I run this only on specific tasks where the task subject is ''Checkin done''

User-added image
ANUTEJANUTEJ (Salesforce Developers) 
try replacing @isTest public static void insertTask()  to @isTest static void insertTask() and use contains(substring) (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm) to check the subject if it contains specific sub string and run for only specific tasks.

Please close the thread by marking this as the best answer so that it can be useful to others in the future.
Ankit Garg 117Ankit Garg 117

Hey Anutej,

Getting the same error but the code coverage is 80%. Here it is. Also, do I need to write @isTest public Boolean contains(String substring) for string as well. Can you please help with this  man.

User-added image



@isTest

public class TestClassForTaskTrigger {
    @isTest
static void insertTask() {
        Account a= new Account();
        a.Name='TestAccount';
        insert a;
    
        Task t = new Task();
        t.WhatId= a.Id ;
        t.Description ='TestDescription';
        insert t; 
    
    FeedItem post = new FeedItem();
    post.ParentId=t.WhatId;
    post.Body = t.Description;
    insert post;

System.assert('TestDescription',post.body);   
}
}

ANUTEJANUTEJ (Salesforce Developers) 
I was able to use the below snippet and test class and 100 percent was covered in my org please do the necessary adjustments as it is a sample snippet.
trigger TaskChatter on Task (before insert)
{
    if(trigger.isbefore && (trigger.isinsert))
    {
        list<FeedItem> listfeed= new list<FeedItem>();
        for(task t:trigger.new)
        {
            if(t.description.contains('Check in Complete')){
                FeedItem post = new FeedItem();
                post.ParentId=t.WhatId;
                post.Body = t.Description;
                listfeed.add(post);}
        }
        if(listfeed.size()>0)
        {
            insert listfeed;
        }}
}
@isTest
public class TaskChatterTest {
    public static testmethod void insertTask() {
        Account a= new Account();
        a.Name='TestAccount';
        insert a;
    
        Task t = new Task();
        t.WhatId= a.Id ;
        t.Description ='Check in Complete';
        insert t; 
    
    FeedItem post = new FeedItem();
    post.ParentId=t.WhatId;
    post.Body = t.Description;
    insert post;
        String pbody= post.Body;

	System.assertEquals('Check in Complete',pbody,'Check Test Class');   
}
}

Please close the thread by marking this as the best answer so that it can be useful to others in the future.
This was selected as the best answer
Ankit Garg 117Ankit Garg 117
Thank you Anutej,

Really appriciate your efforts in sorting this out. 

Cheers