Friday 14 January 2011

Post Event Detail to Parent Chatter Feed

This week I needed to update an account's chatter feed when a new event was created related to it.  Turns out to be quite a short trigger:

trigger PostEventToParentChatterFeed on Event (after delete, after insert, after update) 
{
 List<Event> toProcess=trigger.new;
 
 if (trigger.isDelete)
 {
    toProcess=trigger.old;
 }

 // build a lookup of describe results by key prefix
 Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
 Map<String, Schema.DescribeSObjectResult> descMap=new Map<String, Schema.DescribeSObjectResult>();
    for (Schema.SObjectType sot : schemaMap.values())
    {
      Schema.DescribeSObjectResult descRes=sot.getDescribe();
      String kp=descRes.getKeyPrefix();
      descMap.put(kp, descRes);
    }
    
    List<FeedPost> feedPosts=new List<FeedPost>(); 
    for (Event ev : toProcess)
    {
        FeedPost fpost = new FeedPost();
        
        // if whatId (Opportunity etc) is defined, post to that, otherwise to the event owner
        Id parentId=(null!=ev.whatId?ev.whatId:ev.whoId);
        
        // ensure feed enabled
        String prefix=((String) parentId).substring(0, 3);
        Schema.DescribeSObjectResult descObj=descMap.get(prefix);
        if ( (null!=descObj) && (descObj.isFeedEnabled()) )
        {
         fpost.ParentId=parentId;
             String user=Userinfo.getUserName();
         String action='Created';
         
         // add a link to allow the user to click into the event from the feed
         String linkUrl= '/' + ev.id;
         String title='View Event';
         if (trigger.isDelete)
         { 
          action='Deleted';
          linkUrl='';
          title='';
         }
             else if (trigger.isUpdate)
         {
          action='Updated';
         }
         
          // set the body to a brief summary
             fpost.Body = action + ' event : ' + ev.Subject;
         fpost.LinkUrl=linkUrl;
         fpost.title=title;
             feedPosts.add(fpost);
  }
 }
    
    if (feedPosts.size()>0)
    {
       insert feedPosts;
    }
}

The basic premise is check if the parent object is feed enabled and then post a summary of the event to the parent's chatter feed.    In the case where this event isn't associated with an Account or Opportunity (the whatId is null) it will be posted to the feed of the Contact etc (the whoId) for the event.  This concept can also be applied to tasks and attachments.

Some obvious improvements:

(1) Allow users to mark events as Not for Chatter or similar, as otherwise everything gets posted!
(2) When an event is deleted, find the previous posts in the feed and remove them, otherwise the links in the feed take you to an error page.

Unit tests are left as an exercise for the avid student!

No comments:

Post a Comment