Combine multiple objects within a list

apex-codesalesforcevisualforce

I'm looking to create a single list of records of various sObject types using apex to display to a custom visualforce page. I'm wondering if there is a way to combine multiple objects (case, opportunity, account, etc) within a single list. If not, how do you append the second object to the first in a list using visualforce code? Is there a best practice?

Thanks


So I could use a little more assistance completing this. I have written this:

public class MyController {

    public List<ContactAndCase> ContactsAndCases { get; set; }

    public Opportunity TheOpp{
        get {
        TheOpp = [select Id FROM Opportunity];
        return TheOpp;
        }
        set;
     }
     public Case TheCase{
        get {
        TheCase = [select Id FROM Case];
        return TheCase;
        }
        set;
     }
} 

How do I fill the ContactsAndCases List?

Best Answer

A VisualForce component iterates over a single list. The type of the List, e.g. List<Lead>, dictates what data can be rendered by a VF component.

In order to render Lists of different types, you can either have a separate VF component for each type, e.g.:

<apex:pageBlockTable value="{!contacts}" var="contact">
...
</apex:pageBlockTable>
<apex:pageBlockTable value="{!cases}" var="case">
...
</apex:pageBlockTable>

Or, you can create a new type which holds instances of the different types. Here's a controller example:

public class MyController {
    public List<ContactAndCase> ContactsAndCases { get; set; }

    public MyController() {
        ContactsAndCases = new List<ContactAndCase>();
        // populate ContactsAndCases list
    }

    public class ContactAndCase {
        public Contact TheContact { get; set; }
        public Case TheCase { get; set; }
    }
}

Then, you can iterate over a List<ContactAndCase>:

<apex:pageBlockTable value="{!ContactsAndCases}" var="item">
    <apex:column value="{!item.TheContact.LastName}" />
    <apex:column value="{!item.TheCase.CaseNumber}" /> 
</apex:pageBlockTable>