function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RedSalesRedSales 

Using __r Reference lookups in a trigger

Hello,

 

I have a trigger in which I need to lookup fields using a lookup field.

If I debug/print out value of "Primary_Partner__c" in my trigger this works correctly.  However when I try to lookup fields using "Primary_Partner__r.Name" or similar for other fields I cannot find or obtain the values.  Is there a restriction in triggers from looking up a parent object or could this be related to some settings on the field?

 

Thanks

Navatar_DbSupNavatar_DbSup

Hi,

Try the below code snippet as reference:

 

trigger checkcount on Account (Before Insert,Before Update)

{

     map<id,account> mp=new map<id,account>([select id, Name from account]);

     for(Account acc : Trigger.New)

     {

System.debug( mp.get(acc.ParentAccount__c). Name);

        

     }

}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

sfcksfck

The data held in trigger.new (or trigger.old) does not include parent object data.

 

To access it you will need to get it out of the database yourself.

 

What I would do is get the set of IDs of the records that are being worked on by the trigger, and re-query them with the parent data attached. 

 

set<id> triggerIds = trigger.new.keyset();
list<childObject__c> listWithParentData = [select Primary_Partner__r.Name, Primary_Partner__r.Address from childObject__c where id in :triggerIds];

 Now you can work with listWithParentData as you would work with trigger.new.

sfcksfck

sorry, i meant trigger.newMap.keyset()

Silambarasan VeluSilambarasan Velu
Hi SFCK,
your logic works fine with new values. what about old values?
Actually I need to access old referance value on after update trigger. any better way?