Categories
Salesforce

Overcoming Limited Feed Tracking in Salesforce

I got a requirement where a client wanted feed tracking for every change that users are doing. Salesforce limits Feed Tracking to 20 fields per object.

Recently I got a requirement where a client wanted feed tracking for every change that users are doing. Salesforce limits Feed Tracking to 20 fields per object.

I have used FieldSet and After Update trigger on object (for which we want to do feed tracking) to overcome the 20 field limit.

What is feed tracking?

The below Salesforce documentation link will explain in detail:
https://help.salesforce.com/apex/HTViewHelpDoc?id=collab_feed_tracking_overview.htm&language=en

Example: Account Feed tracking

IMP: Enable Feed Tracking by:
setup -> Chatter -> FeedTracking -> Select Account -> Click on Enable Feed Tracking

  1. Create field set on Account called AccountChatter. Add the fields you want to track in feed tracking.
  2. Create the following after update trigger on Account:

Add fields in FieldSet:

trigger AccountChatter on Account (after update) {
    List<Schema.FieldSetMember> lstTrackedFields = SObjectType.Account.FieldSets.AccountChatter.getFields();

    if (lstTrackedFields.isEmpty()) return;
    
    List<FeedItem> lstFieldChanges = new List<FeedItem>();
    
    if(!trigger.isUpdate) return;
    
    for (Account objNewAccount : trigger.new) {

        final Account oldAccount = trigger.oldmap.get(objNewAccount.Id); 
        // Iterate over all fields in Fieldset 
        for (Schema.FieldSetMember objField : lstTrackedFields) {
            String fieldName  = objField.getFieldPath();
            String fieldLabel = objField.getLabel();

            if (objNewAccount.get(fieldName) == oldAccount.get(fieldName))
                continue;

            String oldValue = String.valueOf(oldAccount.get(fieldName));
            String newValue = String.valueOf(objNewAccount.get(fieldName));

            if (oldValue != null && oldValue.length()>255) 
                oldValue = oldValue.substring(0,255);

            if (newValue != null && newValue.length()>255) 
                newValue = newValue.substring(0,255); 

            FeedItem post = new FeedItem();
            post.ParentId = objNewAccount.Id; // RecordId
            post.Body = UserInfo.getName()+' changed '+fieldLabel+' from '+oldValue +' to '+newValue ;

            lstFieldChanges.add(post);
        }
    }

    if (!lstFieldChanges.isEmpty()) insert lstFieldChanges;

}

Output:

Create Record in Account with Name: Ajay test chatter

Now update the record with Name: Ajay test verified

The above solution has been implemented by taking idea from below post:
(To overcome the limit of History Tracking)
http://salesforce.stackexchange.com/questions/39956/what-is-the-best-workaround-for-the-20-field-history-tracking-cap

Happy Coding!!! Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *