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
David SomekhDavid Somekh 

Accessing Fields From a Lookup Relationship Object

Hello Apex Wizards (-: I

 

I have an annoying problem.

 

In our system we have an object called “Dongles” and this object has a reference field(Lookup Relationship) to the account object named customer_c.

 

I have a case on dongle save where I need to take a value from the account related to it and put it in the dongle record.

 

I am assuming it’s possible to get the data of the account(that is related to the dongle) without doing an extra query (As we know, apex is very cheap on queries :smileyvery-happy:) but when I try to get a pointer to the account object using the syntax below I get a null object.

 

Account AccountPointer = dongleToSync.Customer__r;

 

Anyway, I figure there is a way to get over this hump without making an extra query. But I could be wrong )-:

 

Any help will be greatly appreciated….

Imran MohammedImran Mohammed

If you are just trying to get the account id, then you should use Customer__c as below

Account AccountPointer = dongleToSync.Customer__c;

 

You can get the detailsof Account using Customer__r.field1__c.

The above line will not be true in Trigger as the entire object graph will not be known at that moment.

EalesieEalesie

Hi

 

Your best option is to create a formula field on your dongle object that retrieves the field you require from your associated Account record. 

 

This way, not only can you access the value in apex but also add it to page layouts, use in eMail templates etc, etc.

 

Hope this helps

 

Ealesie

David SomekhDavid Somekh

Thank You Emran And Ealesie!

 

In the end I managed to solve it by using a formula field with the value I need.

 

Thanks Guys!

Imran MohammedImran Mohammed

Will be great if you post the code for what you have done, as it will be useful for forum users.

Abhishek KedariAbhishek Kedari
Hi David,
 
    I am facing same issue. I am trying something like this in my apex class 
 
    System.debug('I M WRITTING  OPP :  ' + shipment.Related_Opportunity__r.Account.Name);

when i save my shipment object, i want to get Account name before I save the shipment object and shipment object contains formula for this relationship as shown below.

User-added image



    But its returning null value.
    Can you please tell me how you resolve this issue?


Thanks,
Abhishek