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
mahesh padigela 1mahesh padigela 1 

Need help on writing wrapper classes to display accounts and contacts in VF page.

Hi,
I am need to to salesforce, I am writing a visualforce page to display check boxes and list of accounts with a process button. Upon slecting the accounts and the check boxes the process button should contain a method which displays the list of contacts related to selected accounts.
I am unable to retrieve the list of contact names using the selected accounts.I am getting an error when i use a soql query to retrieve the contacts using the account id.

Below is my apex code for above requirment.
Please let me know if my question is not clear.


public class accountcontactwrap {
 public list<accountwrap> warpacc{get;set;}
 public list<account> selectedAccounts{get;set;}
 public list<contact> cont{get;set;}
// public list<contactwrap> wrapcon{get;set;}
  public accountcontactwrap(){
   warpacc=new list<accountwrap>();
   for(account ab:[select id,name,phone from account limit 10]){
    warpacc.add(new accountwrap(ab));
   }
  }
  
public void showcontacts(){
cont=new list<contact>();
 for(accountwrap warpobj:warpacc)
 {
  if(warpobj.isSelected==true){
  cont=[select lastname from contact where account.id=warpobj.acc.id];
   
  }
 }
}

 public class accountwrap{
 public account acc{get;set;}
 public boolean isSelected{get;set;}
  public accountwrap(account a){
   acc=a;
   isSelected=false; 
  }
Best Answer chosen by mahesh padigela 1
Ravi Dutt SharmaRavi Dutt Sharma
Your query on Contact is referencing incorrect field. It should be AccountId instead of Account.Id
 
cont=[select lastname from contact where AccountId =: warpobj.acc.id];

Also, you should avoid writing SOQL in for loop.

All Answers

Ravi Dutt SharmaRavi Dutt Sharma
Your query on Contact is referencing incorrect field. It should be AccountId instead of Account.Id
 
cont=[select lastname from contact where AccountId =: warpobj.acc.id];

Also, you should avoid writing SOQL in for loop.
This was selected as the best answer
mahesh padigela 1mahesh padigela 1
@Ravi

Also please suggest me how to write the above soql code outside the for loop, because i am taking each account from a list and for every account i am fetching the contacts list, i couldn't find another way to write soql outside for loop. However in this scenario i am limiting the number of account records fectched by 10,but i wanted to know in realtime how do you avoid writing soql queries in For loop.

Thanks in advance