Please find below an example of how to accomplish this.
I've included 2 ways to do this:
Using a single query
Using a wrapper class My controller (AccountContactWrapperController.class):
public class AccountContactWrapperController {
public List<Account> accounts{get;set;}
public List<ACWrapper> ACWrappers{get;set;}
public AccountContactWrapperController(){
this.ACWrappers = new List<ACWrapper>();
this.accounts = new List<Account>();
//Get Accounts & Related Contacts in 1 query
List<Account> accs = [Select Id, Name, (Select Id, FirstName, LastName From Contacts) From Account Limit 1];
this.accounts = accs;
//Get Accounts & Contacts in separate queries for Wrapper
List<Account> accsForWrapper = [Select Id, Name From Account Limit 1];
List<Contact> consForWrapper;
Account acc;
if(accsForWrapper != null && !accsForWrapper.isEmpty()){
acc = accsForWrapper.get(0);
consForWrapper = [Select Id, FirstName, LastName From Contact Where AccountId =:acc.Id];
}
if(consForWrapper != null){
ACWrapper wrapper = new ACWrapper(acc, consForWrapper);
this.ACWrappers.add(wrapper);
}
}
public class ACWrapper{
public Account account{get;set;}
public List<Contact> contacts{get;set;}
public ACWrapper(Account acc, List<Contact> cons){
account = acc;
contacts = cons;
}
}
}
My VF page (AccountContactWrapperTest.page):
<apex:page controller="AccountContactWrapperController" >
<apex:form >
<!--Display Account & Contact info from 1 Query-->
<apex:pageBlock title="Info From Query">
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:Column value="{!a.Name}" />
<apex:Column headerValue="Contact Names">
<apex:repeat value="{!a.Contacts}" var="c">
{!c.FirstName} {!c.LastName} <br />
</apex:repeat>
</apex:Column>
</apex:pageBlockTable>
</apex:pageBlock>
<!--Display Account & Contact info from 1 Wrapper class-->
<apex:pageBlock title="Info From Wrapper class">
<apex:pageblocktable value="{!ACWrappers}" var="w">
<apex:Column value="{!w.account.Name}" />
<apex:column headervalue="Contact Names">
<apex:repeat value="{!w.contacts}" var="c">
{!c.FirstName} {!c.LastName} <br/>
</apex:repeat>
</apex:column>
</apex:pageblocktable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:
No comments:
Post a Comment