Combine multiple objects within a list

我与影子孤独终老i 提交于 2019-12-11 02:39:10

问题


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.



来源:https://stackoverflow.com/questions/8157240/combine-multiple-objects-within-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!