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
ARUL BERNARD I 6ARUL BERNARD I 6 

Too many SOQL queries I am using in wrapper class

Hi Please help me out to solve this problem.
public class wrapperExample{

 
  public List<Wrapper> wrapAccountList {get; set;}

 public wrapperExample(){
  if(wrapAccountList == null) {
  wrapAccountList = new List<Wrapper>();
  for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 100]) {

          for(list<contact> r: [select Id, Name from Contact where AccountId = :a.Id]){

wrapAccountList.add(new Wrapper(a,r));
 
  }   
  }
  }
  }

 public class Wrapper{

 public Account acc {get; set;}
  public List<Contact> con {get; set;}

 public Wrapper(Account a, List<Contact> c) {
  acc = a;
  con = c;

 }
  }
 }
Manj_SFDCManj_SFDC
Hi Arul,
your this line   for(list<contact> r: [select Id, Name from Contact where AccountId = :a.Id]){
is causing the problem
in this for loop 
for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 100]) 
add the account ids to a set and use that it in the where clause of 
for(list<contact> r: [select Id, Name from Contact where AccountId = :a.Id]){

this should fix it
 
Gustavo BertolinoGustavo Bertolino
The query on Contact is inside a for loop and this is throwing the error message. Avoid putting SOQL queries inside for loops as Salesforce development best practice.
v varaprasadv varaprasad
Hi Arul,

Please check following snippet code : 
 
public class wrapperExample {


 public List < Wrapper > wrapAccountList {
  get;
  set;
 }

 public wrapperExample() {
  if (wrapAccountList == null) {
   wrapAccountList = new List < Wrapper > ();
   List < account > accList = [select Id, Name, BillingState, Website, Phone, (select Id, Name from Contacts) from Account limit 100];

   for (Account a: accList) {
   if(a.contacts.size() > 0){
     list < contact > conist = a.contacts;    
     wrapAccountList.add(new Wrapper(a, conist));
    }

   }

  }
 }
}


Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com


 
ARUL BERNARD I 6ARUL BERNARD I 6
Hi Varaprasad,
I need to code without using sub-query