[SalesForce] SObject row was retrieved via SOQL without querying the requested field on Contact.Account

I am getting this error:

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

Controller:

public class WrapperAccountCtrl {

    public List<Account> acclist{get;set;}
    public List<Contact> conlist{get;set;} 
    public List<MyWrapper> wap{get;set;}

    public WrapperAccountCtrl() 
    {
        acclist=[Select id,name from Account];

        conlist=[Select id,name,AccountID  from contact where AccountID IN:acclist];

        system.debug('Size----'+conlist.size());

         wap=new List<MyWrapper>();

         for(integer i=0;i<acclist.size();i++)
         {
             wap.add(new MyWrapper(conlist,acclist[i]));
         }
    }

    public class MyWrapper
    {

        public Account accn{get;set;}

        public List<Contact>conrec{get;set;}

        public MyWrapper(List<Contact> con,Account acc)
        {
            accn=acc;
            conrec=con;    
        }
    }
}

VF Page:

<apex:page controller="WrapperAccountCtrl" sidebar="false">
      <apex:form >
         <apex:pageBlock >
             <apex:pageBlockTable value="{!conlist}" var="c">
                 <apex:column value="{!c.account.Name}"/>
             </apex:pageBlockTable>
         </apex:pageBlock>
     </apex:form> 
</apex:page>

Best Answer

In your query

conlist=[Select id,name,AccountID  from contact where AccountID IN:acclist];

you queried the id, name and accountId fields only. So, you can display only these fields on the vf page from this list. If you want to display also the Account name, then query the Account.name field also in your query. like this -

conlist=[Select id,name,AccountID, Account.Name  from contact where AccountID IN:acclist];
Related Topic