+ Start a Discussion
Lahari KondadiLahari Kondadi 

SOQL query to fetch the Contact object details of a selected Account record

Hi all,
         I am new to salesforce development.I have to fetch the contact details like FirstName,LastName,Phone,Email,MailingAddress of a selected record of  account object and display it in the tabular format in vf page.
I tried with this query in controller :-
               Private id AccountId;
               this.accountRecord = (Account)controller.getRecord();
              this.AccountId = this.accountRecord.id;
              List<Contact> details= new List<Contact>();
              details = [SELECT FirstName,LastName,Phone,Role__c,Email,MailingAddress FROM Contact WHERE AccountId=:this.AccountId];
       I am getting the required output for few records,and few records its showing "List index out of bounds: 0 " error.
         Please help me with this.


Thanks & Regards,
Lahari
           
Best Answer chosen by Lahari Kondadi
Dutta SouravDutta Sourav
Hi Lahari,

Make sure that the list is not empty before accessing it.

Before referring to the 0th index of list you must perform a check on whether the list is empty or not. Whenever you try to access records from list first check if its empty or not.
 
if(details.size() > 0) {
    // Code realted to details
}
 *If you try to access details[0] without empty check then it will obviously throw that error!!
 
Warm Regards,
Sourav

All Answers

AnupPrakash_AlgoworksAnupPrakash_Algoworks
Try debug 
System.debug(' this.AccountId:: ' + this.AccountId);
Dutta SouravDutta Sourav
Hi Lahari,

Make sure that the list is not empty before accessing it.

Before referring to the 0th index of list you must perform a check on whether the list is empty or not. Whenever you try to access records from list first check if its empty or not.
 
if(details.size() > 0) {
    // Code realted to details
}
 *If you try to access details[0] without empty check then it will obviously throw that error!!
 
Warm Regards,
Sourav
This was selected as the best answer
Lahari KondadiLahari Kondadi
Hi sourav,
               Thanks for the quick reply.The size of details list is only 2. I have more than 2 records in my Account object.  
In my code, this.AccountId refers to the id of the selected Account record. So according to my query all the details of clicked record should get fetched. Why it is not working for few records? And why only for some records??

Thanks & Regards,
Lahari