I have a trigger that creates a chatter post after insert or after update for Tasks. However, I also want to @mention the created by user for the task. How Can I add this? Thanks
trigger ActivityHistoryToChatter on Task (after insert, after update) {
for(Task t : trigger.new)
{
//if it's now a completed task, and wasn't before
//create the new chatter post.
string what = t.whatID;
if(what.substring(0,3) == 'a19')
/*
The above line lets you control exactly which objects you want to toss this on. Adjust the If statement to the
3 digit object code for various elements.
Ex:
Cases - 500
Accounts - 001
Opportunities - 006
I STRONGLY suggest you use this if you're going to do a larger, longer demo, as you'll need to chatter enable any
object you play with the task history on or this will crash. If you're not playing with Activity History/Tasks anywhere
else, won't be a big deal.
*/
//{
if(!t.alreadyPosted__c && t.status == 'Completed')//hasn't been posted, completed
{
Task daTask = [select id, description, whoid, activityDate, ownerid, subject from Task where id = :t.id];
string whoelement = daTask.whoId;
if (whoelement != NULL)
{
if(whoElement.substring(0,3) == '003')//contact
{Contact who = [select name from Contact where id = :whoelement];
whoElement = who.name;}
else
{Lead who2 = [select name from Lead where id = :whoelement];
whoElement= who2.name;}
}
User owner = [select name from User where id = :daTask.OwnerId];
daTask.alreadyPosted__c = true;
FeedPost OppFeed = new FeedPost();
string body = t.Subject + ' was completed by ' + owner.name + ' on ';
body += t.activityDate.Month() + '/' + t.activityDate.Day() + '/' + t.ActivityDate.Year() + '\n';
if(t.description != null)
body += 'Comments: ' + t.description;
OppFeed.body = body;
oppFeed.parentID = t.whatID;
oppFeed.linkURL = '/' + t.id;
oppFeed.title = t.subject;
insert oppFeed;
}
//}
}