Combine multiple objects within a list

2019-07-20 20:09发布

问题:

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?

回答1:

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>


回答2:

Jeremy's wrapper class is what you want. In addition, you'll generate SOQL-based lists of the objects you want first and then loop through to create new wrapper instances for your wrapper list (ContactsAndCases in this case) containing values from both contacts and cases.



回答3:

Maybe I am missing something but couldn't you simply collect them in:

List<SObject> objects = new List<SObject>();  

You can then add any generic SObject into that list.