loading... Salesforce Cat

Thursday, November 6, 2014

Salesforce History Tracking :Access Field History From Apex Code


In my last post Salesforce History Tracking - Step by Step Guide I discussed in detail about enabling history tracking on a custom object and viewing those logs using Salesforce reports and History tracking related list.In this post I am going to discuss how field tracking logs can be accessed from Apex code.

Salesforce maintains separate internal object to maintain history logs for each history tracking enabled object.The naming of these tables follows a simple convention so should be easy to find. For standard objects the name of the history table follows the format: '<ObjectName>History' so for the Account object the history table is AccountHistory.

For custom objects the name of the convention simply replaces the 'c' on the end of the API name with 'History'. So, for a custom object call My_Object__c the history table is called My_Object_History.

All history tracking tables has following fields.


  • ParentId : This is the Id  of record this history tracking log is related to (id of record field modification happend)
  • Field      :  API name of the modified field.
  • OldValue : Field value prior to the modification.
  • NewValue : Field value after modification
  • CreatedById : Id of the User who made the modification. 
History Tracking logs can be queried via SOQL as shown below

Query all field modification logs of a custom object called  My_Object__c

 Select Id,Field,CreatedById ,OldValue,NewValue,EditedBy From My_Object__History  

Query All field modification logs related to a field called My_Field__c of My_Object__c



 Select Id,Field,CreatedById ,OldValue,NewValue,EditedBy From Friend__History   
 Where Field ='My_Field__c'  


Query  All field modfication logs related to a particular record

 
 Select Id,Field,CreatedById ,OldValue,NewValue,EditedBy From Friend__History   
 Where ParentId=:RecordId   


Using SOQL to query history logs you can build your own Visualforce pages to display field modification details to the end users. 

1 comment:

  1. Field : API name of the modified field.
    I want the Field label instead of the API name, any idea?

    ReplyDelete