I have history tracking enabled for a custom object. Can I write trigger trigger on the new History tracking of my custom object? I am not getting such example from google nether do I get somewhere it is not possible.
3 Answers
You can have Apex Batch Job where you can Query the history and add your logic.
Use Below Query to get the rows
Select ID,Field,OldValue,NewValue,createddate From CucstomObject__History
where Field = 'CustomObjectFieldName' and parentId = :CucstomObject.Id
order by createddate
As @KirillYunussov states, there are no triggers on field tracking history objects. If you are trying to monitor changes in field history tracking objects, you will need an Apex scheduled job that periodically trolls through the parent records, based on last modified date. Then you can SOQL query the child field history records and do something.
One caveat - field history tracking records can't be inserted in testmethods (mocked or DML'd) leaving the ugly alternative of
(1) pre-existing org data and @isTest(SeeAllData=true)
or
a less ugly alternative ...
(2) an interface that returns a wrapper class that is a facade onto of the xxxHistory
object. The PROD implementation of this interface copies values from the SOQL result fields into your wrapper variables. The TEST implmentation of this interface simply mocks the values directly into your facade wrapper variables
Note, you would think you could use JSON.deserialize to create OldValue
and NewValue
, but the following, at V38, yields a GACK
AccountHistory[] ahs = (AccountHistory[]) Json.deserialize(
'[{"OldValue": 10}]',
List<AccountHistory>.class);
System.UnexpectedException: Salesforce System Error: 715868465-363034 (1566461472) (1566461472)
-
the big issue with #2 is that the OldValue and NewValue fields are readonly and you cannot mock test values into them– willardCommented Oct 4, 2016 at 17:27
-
It is not possible. You could, however, query the history objects from the parent object's trigger.
For example, you have an after-update trigger on Account, from which you can query AccountHistory object.