http://www.radialweb.com/2010/09/adding-activity-to-a-chatter-feed-using-triggers/
Below is a copy of the code Kevin posted:
trigger ChatterActivity on Task (after insert, after update) {
List<FeedItem> feedItems = new List<FeedItem>();
//We want to show the User name as assignedTo. The only way to get to that is by querying the user table.
Set<ID> ownerIds = new Set<ID>();
for (Task t : Trigger.new) {
ownerIds.add(t.ownerId);
}
Map<ID,User> userMap = new Map<ID,User>([SELECT ID, Name FROM User WHERE ID IN :ownerIds]); //This is our user map
//Now loop though the new/updated tasks and create the feed posts
for (Task t : Trigger.new) {
if (t.WhatId != null) {
FeedItem fitem = new FeedItem();
fitem.type = 'LinkPost';
fitem.ParentId = t.WhatId;
fitem.LinkUrl = '/' + t.id; //This is the url to take the user to the activity
fitem.Title = 'View'; //This is the title that displays for the LinkUrl
//Get the user by checking the userMap we created earlier
User assignedTo = userMap.get(t.ownerId);
fitem.Body = ((Trigger.isInsert) ? 'New' : 'Updated') + ' Activity ' + ((t.ActivityDate != null) ? t.ActivityDate.format() :'')
+ '\nAssigned To: ' + ((assignedTo != null) ? assignedTo.name : 'Unknown')
+ '\nSubject: ' + t.Subject
+ '\nStatus: ' + t.Status;
feedItems.add(fitem);
}
}
//Save the FeedItems all at once.
if (feedItems.size() > 0) {
Database.insert(feedItems,false); //notice the false value. This will allow some to fail if Chatter isn't available on that object
}
}
And here is the test class associated
public with sharing class ChatterUnitTests {
/*
* Test the ChatterActivity trigger which inserts chatter feed posts whenever a task is inserted on the parent object
*/
public static testMethod void testChatterActivity() {
//create the test account
Account a = new Account(name='Test Account');
insert a;
//create a task on that account
Task t = new Task(whatId=a.id);
t.Subject = 'This is a test activity for chatter';
t.ActivityDate = System.today();
t.Status = 'In Progress';
t.Description = 'Hello, this will be chattered';
insert t;
//Make sure Account has the feed enabled. If it does, make sure the chatter feed post is there
Schema.DescribeSObjectResult r = Account.SObjectType.getDescribe();
if (r.isFeedEnabled()) {
List<AccountFeed> posts = [SELECT Id, Type FROM AccountFeed WHERE ParentId = :a.id];
System.assertEquals(1, posts.size());
}
}
}
No comments:
Post a Comment