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
Abdul Mujeeb ShaikAbdul Mujeeb Shaik 

Displaying related contacts of Accounts using Wrapper class only

Hi i need to dispaly all Account names & the related contacts, using a wrapper class,

i tried this , but it still have a bug unable to realted the accountid in contact ,
my code

<apex:page controller="conacc" >

<apex:form >
    <table>
             <apex:repeat value="{!wrapper}" var="wrap">
            <apex:repeat value="{!wrap.conRec1}" var="w">
            <tr>
                <td>
                <apex:outputText value="{!wrap.accRec1.Name}"/>
                </td>                


          
             <td>
                          <apex:outputfield value="{!w.name}"/> 
               </td>
               </tr>
            </apex:repeat>
            </apex:repeat>
   </table>   
</apex:form>
</apex:page>
 

apex code
 

public with sharing class conacc {

  
    public List<MyWrapper> wrapper {get; set;}

  public List<Account> accLst1 {get; set;}

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

    public conacc ()

    {
    
      accLst1 = [select id,Name from Account  ] ;


       conLst1 = [select Id,Name from contact where AccountId IN : accLst1 ] ;

      

        wrapper = new List<MyWrapper>() ;
       for(Integer i=0 ; i < 20; i++)

            wrapper.add(new MyWrapper(  conLst1, accLst1[i])) ;

    System.debug('----------'+ wrapper);
       

    }

public class MyWrapper

    {

        public Account accRec1 {get; set;}

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

        

        public MyWrapper( List<Contact> con ,Account acc )

        {

            accRec1 = acc ;

            conRec1 = con ;

        }

}


}
just displaying account names & contacts , please correct me where i am doing mistake 


 

Swati GSwati G
Dont query account seperatly and why do you need wrapper. You can bind the below contact list on page directly and use account's fields.

conLst1 = [select Id,Name,Account.Name, AccountId from contact ] ;

 <table>
            <apex:repeat value="{!conLst1}" var="c">
                <tr>
                     <td>
                        <apex:outputText value="{!c.account.Name}"/>
                    </td>                
                    <td>
                        <apex:outputfield value="{!c.name}"/> 
                   </td>
                  </tr>
                </apex:repeat>
</table>