John
John

Reputation: 1

Display data from multiple objects in a Salesforce VF page in one pageblocktable

I have a requirement to display records from 2 objects (Account & Contact) in a single pageblocktable in a Salesforce VF page, Account records followed by Contact records. I know that we can achieve this using a wrapper class, but all the examples I came across talked about displaying checkbox or displaying columns vertically(not horizontally) from different objects in a pageblocktable.

Would appreciate any pointers/code samples. Thanks!!

        Object    Name                  Phone           Email

Record 1 - Account - Account Name - Account Phone -Account Email

Record 2 - Contact - Contact First Name - Contact Phone -Contact Email

Upvotes: 0

Views: 4397

Answers (1)

Murthy VVR
Murthy VVR

Reputation: 11

I found a dirty way of doing this. This may not be the best answer, but you can achieve the required functionality as follows. Create a two dimensional array and store different object's data as strings. Then iterate over the array in visualforce page to display the data.

public class MixedObjectVFController {

public static List<List<String>> getObjectList(){
    List<List<String>> strList = new List<List<String>>();
    List<Account> acc = [select name,phone from account limit 2];

    for(account a : acc){
        List<String> tempList = new List<String>();
        tempList.add('account');
        tempList.add(a.name);
        tempList.add(a.phone);
        strList.add(tempList);
    }
    List<contact> cList = [select name,phone from contact limit 2];
    for(contact a : cList){
        List<String> tempList = new List<String>();
        tempList.add('contact');
        tempList.add(a.name);
        tempList.add(a.phone);
        strList.add(tempList);
    }
    return strList;
} }

and Visualforce page

<apex:page controller="MixedObjectVFController" >
<apex:pageBlock>
    <apex:pageBlockSection>
        <apex:pageBlockTable value="{!objectList}" var="item">
            <apex:column headerValue="Object" value="{!item[0]}" />
            <apex:column headerValue="Name" value="{!item[1]}" />
        </apex:pageBlockTable> 
    </apex:pageBlockSection>
</apex:pageBlock>

Make sure to check for nulls while using the indices.

Upvotes: 0

Related Questions