When you track a lookup field, the old and new values are ids. Is there any way to find out what the name of the lookup object is from that id on the history object?

Trying to avoid having to get all the ids and then do queries on the associated objects, which is the more brute force way.


Let's assume you are history tracking on the Contact.AccountId field, then the ContactHistory records will look like

Field      OldValue             NewValue
Account    0016300000fDQRdAAO   0016300000fDQReAAO 
Account    Fred Fubar           Francis Fubar

so ...

  • Take OldValue (or NewValue) and convert to an Id; if an exception, ignore as that would be the Name fieldvalue of the Lookup object
  • Then use method getSobjectType() to find the parent record sobjecttype

    for (ContactHistory ch: [Select Field, OldValue, NewValue FROM ContactHistory]) {
      switch on ch.Field {
       when 'Account', '...', '...' {
        try {
         Id sobjOldId = (ID) ch.OldValue;
         Id sobjNewid = (ID) ch.NewValue;
         SObjectType oldSobjType = sobjOldId.getSObjectType();
         SObjectType newSobjType = sobjNewId.getSObjectType();
         catch (Exception e) {}  // ignore
       when else {} 

Since I don't know what you intend to do with the sobjectTypes, the above code could be restructured in different ways.

  • Thanks for the reply. Im less concerned with what the object type of the field is as what the actual name of the field is. E.g. I have a lookup to a custom Employee__c object. Each Employee has a name. In the History object there is only the id of the employee. But I want to get the value that changed. So in my lookup I changed from John to Tom. I want that the value of the Lookup is Tom, not the id of his employee, which is what is stored in the history object. I was just wondering if there was an easy method of getting the name of the employee Oct 31 '19 at 19:52

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.