2

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.

  • what's your use case ? why do you want trigger on history object ? – Vamsi Krishna Gosu Jul 6 '15 at 11:59
  • I just want to know if that can be done. I can handle that by trigger on object. – Testing_SFDC Jul 6 '15 at 12:44
1

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
3

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 – willard Oct 4 '16 at 17:27
  • @willard; amended answer. Good point – cropredy Oct 4 '16 at 21:35
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.