[SalesForce] Get Opportunity’s Account


Why I can't access to opportunity account name on apex/vf ?


I'm creating a opportunity VF page, extending the standarcontroller:

 <apex:page standardController="Opportunity" extensions="test1Extension">

On my extension class I'm setting the opp object using:

 opp = (Opportunity) controller.getRecord();

When I try to reference account on the vf by {!opp.Account.Name} I get this error:

SObject row was retrieved via SOQL without querying the requested
field: Opportunity.Account

In addition, I've tried to query the account using a subquery:

opp =[select Id, (select Id from Account where Id= opportunity.AccountId) from Opportunity where id=:opp.Id];

Or Account acc = [select Id from Account where id=:opp.AccountId];

SObject row was retrieved via SOQL without querying the requested
field: Opportunity.AccountId


1) Why I can't reference Account from Opportunity ?
2) What is the proper why to make that sub-query?

thx in advance

Best Answer

Since you have the standard controller there you can refer to fields through that and they will be automatically queried. In this case you would refer to


on the VF and that would work.
The prefix Opportunity. is referring to the standard controller (rather than your extension variable Opp.
Any fields that you include on the VF page from the Standard Controller (Opportunity.) will be automatically queried. You don't need to do anything in your extension to make that data available.

If you had wanted to use your own variable Opp on the page (to have Opp.Account.Name), you were nearly there with the approach you had you just needed to phrase the query correctly, the syntax you would want is

Opp = [select id, account.name from opportunity where id=:opp.Id]
Related Topic