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
Abhishek KedariAbhishek Kedari 

Accessing variables of object which is part of current object

Hi All,

   I want to access variables of object which is part of current object in my apex class.
           Shipments__c shipment       where Shipments__c contains object opportunity as one of its field. Suppose oppourtunity field contains field name. How I can access these fields (id and name) of opportunity using shipment object variable.  /  /

but its not working and saying id and name does not exist.

Can anyone please help me with this?
Let me know if I am not clear with the question.


You need to make sure you understand how relationships work, please go through below link

For your query, it should be something like shipment.Opportunity__r.Id & shipment.Opportunity__r.Name

before doing this you need to retrieve them in your SOQL though,

Shipments__c shipment = [Select Id, Name, Opportunity__r.Id, Opportunity__r.Name from shipment LIMIT 1];

Hope this helps
James LoghryJames Loghry

Kartik is correct in that you'll need to use __r and requery for the Opportunity relationships, but his example isn't 100% accurate.  You'll need to pass in the Shipment Id into the query as well.  

That being said, how are you retrieving Shipment?  Does your Apex class act as an extension controller?  If so, the query and extension controller might look like the example below.  Please note that Opportunity__c, Opportunity__r.Id are synonymous in this example.

public class MyShipmentExt{

    public Shipment__c shipmentRecord {get;set;}

    public MyShipmentExt(ApexPages.StandardController ctrl){
        shipment = 
                Id = :ctrl.getId()];

Abhishek KedariAbhishek Kedari
Hi Kartik and James,

    Thanks a lot for directing me in right direction but I am still stuck with this issue.

Apex code : 
    System.debug('I M WRITTNG   :  ' + shipment.Related_Opportunity__r.Account.Name);

Debug Log :
   14:58:44.271 (271899101)|USER_DEBUG|[63]|DEBUG|I M WRITTNG   :  null

How I am creating new shipmenet object - 
1 ) Create new account
2) Inside account there is a field call Opportunity
3) Every opportunity has shipment object associated with it.

User-added image

User-added image

I expect to see account name for any particular shipment as account and opportunity are already created and I am creating new shipment inside this opportunity, 

I am accessing values getting passed from viualforce page to my apex class.
Do I need to populate the value in visualforce manually or it will get populate automatically ?