Sunday 13 May 2012

Feed Tracking more than 20 fields in an Object

Please refer to my previous posts regarding Feed Tracking and Chatter Approvals for better understanding.

We all know that, Feed Tracking is greatly used to expose the changes of a field in an Object via Chatter Posts on successful save of the record.

Whenever a field change occurs, then Chatter Posts will be added automatically on behalf of the User consisting of,

1. Field Name

2. Old Value of the Field

3. Newly updated value of the Field

Feed Tracking can be enabled for only 20 fields in an object. This posts illustrates a simple work around using Trigger to overcome the 20 field limit.
// Triggered whenever a Opportunity is Updated and Saved
trigger ChatterUpdatesOppty on Opportunity (after update) 
{
  List<feeditem> fi=new List<feeditem>();
  List<entitysubscription> es=new List<entitysubscription>();
  Boolean flag=false;
  for (Opportunity o : trigger.new)
  {
    if(o.DeliveryInstallationStatus__c!=
              System.Trigger.oldMap.get(o.Id).DeliveryInstallationStatus__c)
    {           
      FeedItem f=new FeedItem();
      f.ParentId=o.Id;
      f.Title=o.Name;
      f.Type='TextPost';             
      f.Body='changed Delivery/Installation Status from '+
              System.Trigger.oldMap.get(o.Id).DeliveryInstallationStatus__c+
              ' to '+o.DeliveryInstallationStatus__c;                            
      f.CreatedById=o.LastModifiedById;
      fi.add(f);            
      // CHECKING WHETHER USER IS ALREADY FOLLOWING THE RECORD OR NOT            
      for(EntitySubscription eee:[Select Id, ParentId, SubscriberId, 
          CreatedById, CreatedDate, IsDeleted FROM EntitySubscription where ParentId like '006%'])
      {
        if( eee.ParentId==o.Id && flag==false)
        {
          //YES, USER IS FOLLOWING THE RECORD
          flag=true;
        }
      }                      
      if(flag==false)
      {    
        //MAKING USER TO FOLLOW THE RECORD
        EntitySubscription hi=new EntitySubscription();
        es.add(new EntitySubscription(ParentId=o.Id,
               SubscriberId=o.LastModifiedById));                
      }
    }
  }    
  insert fi;                    
  insert es;
}
This trigger additionally incorporate a method to add the User as a Follower of the record automatically making him/her to receive updates when someone added a comment to the Feed. Hence using this Trigger, any number of fields can be Feed Tracked and can be considered as an alternative to Standard Salesforce Feed Tracking.

No comments:

Post a Comment