Dynamic Record Display – How to display record of any sObject on same Visualforce Page?

Do you have a requirement to show all object’s record on the same page? Well, this article can be useful if you are looking for this solution. This solution will work with all standard and custom object.

I have used 2 picklist field as solution approach for this requirement so that It will be easy to select sObject and record.

  • Picklist 1 will display all sObject (standard and custom) from you org.
  • Once you select the sObject, Picklist 2 will display records from that sObject with Name and Id.
  • Once you will select any of the record, the page will show complete details about that record.

 

ApexClass Code:

public class DynamicObjectExampleController {

    public String selectedSObject {get;set;}

    

    List<SelectOption> recordList {get;set;}//this list will hold record from selected sObject

    public String selectedRecord {get;set;}

    

    public Id selectedRecordId {get;set;}

    /*

    This method will add all sObjectName in sObjectNames list

    */

    public List<SelectOption> getSObjectNames(){

        List<SelectOption> sObjectNames = new List<SelectOption>();

        sObjectNames.add(new SelectOption('Select sObject', 'Select sObject'));

        for ( Schema.SObjectType type : Schema.getGlobalDescribe().values() ) {

            sObjectNames.add(new SelectOption(String.valueOf(type), String.valueOf(type)));//Fetch object name and add in selectoption list

        }

        return sObjectNames;

    }

    

    /*

     * This method will fetch available records in sObject upto 100 records

     * Modify soql filter and limit based on your need

     * You need to make sure the SOQL does not timeout and does not impact performance

     */

    public PageReference generateRecordList(){

        try{

            if(selectedSObject != null && selectedSObject != ''){          

                String recordQuery = 'SELECT Id, Name FROM '+selectedSObject+' LIMIT 100';

                List<sObject> records = Database.query(recordQuery);

                recordProcessing(Database.query(recordQuery), true);

            }

        } catch(Exception e){

            ApexPages.Message myMsg;

            try{

                String recordQuery = 'SELECT Id FROM '+selectedSObject+' LIMIT 100';

                recordProcessing(Database.query(recordQuery), false);

                myMsg= new ApexPages.Message(ApexPages.Severity.ERROR,'Selected sObject does have "Name" Field!!'

                                                            +'\nFetching only Id fields now');

            ApexPages.addMessage(myMsg);

            } catch(Exception e1){

myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Select valid sObject');

                ApexPages.addMessage(myMsg);    

            }

        }

        return null;

    }

    

    /*

     * This function will get recordId from selected record

     * */

    public PageReference changeSelectedRecord(){

        System.debug('function called');

        if(selectedRecord != null && selectedRecord != ''){

            if(selectedRecord.contains('-')){

            selectedRecordId = (ID)selectedRecord.split('-')[1].trim();

            } else{

                selectedRecordId = (ID)selectedRecord.trim();

            }

            System.debug('select record id---'+selectedRecordId);

        }

        return null;

    }

    

    /*

     * This method will do post processing on fetched records

     * */

    public void recordProcessing(List<sObject> records, boolean nameIncluded){

        if(recordList == null){

            recordList = new List<SelectOption>();

        } else{

            recordList.clear();

        }

        for(sObject sObj : records){

            String recordName;

            if(nameIncluded){

            recordName = String.valueOf(sObj.get('Name'))+' - '+String.valueOf(sObj.get('Id'));

            } else{

                recordName = String.valueOf(sObj.get('Id'));

            }

            recordList.add(new SelectOption(recordName, recordName));

        }

        

        if(recordList.size() == 0){

            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'No record found for this sObject!!');

            ApexPages.addMessage(myMsg);

        }

    }

    

    public Id getSelectedRecordId(){

        return selectedRecordId;

    }

    

    public List<SelectOption> getRecordList(){

        return recordList;

    }

}

 

Visualforce Page Code:

<apex:page controller="DynamicObjectExampleController" sidebar="false">

    <apex:form id="pageForm">

        <apex:pageMessages />

        <apex:selectList label="Select Object Name" title="Select Object Name" multiselect="false" value="{!selectedSObject}" size="1">

            <apex:actionSupport event="onchange" action="{!generateRecordList}" reRender="pageForm"/> 

            <apex:selectOptions value="{!SObjectNames}"/> 

        </apex:selectList>

        <apex:selectList label="Select Record" title="Select Record" multiselect="false" value="{!selectedRecord}" size="1" rendered="{!recordList !=null && recordList.size>0}">

            <apex:actionSupport event="onchange" action="{!changeSelectedRecord}" /> 

            <apex:selectOptions value="{!recordList}"/> 

        </apex:selectList>

        <apex:outputPanel title="Record Detail" id="recordHolder">

            <!-- apex:detail will display all the details of the record -->

            <apex:detail subject="{!selectedRecordId}" />

        </apex:outputPanel>

    </apex:form>

</apex:page>
Output

 

You may have to do modify the code as per your need and implement extra error handling based on your requirement however the basic logic will remain same. You can add this page as Visualforce Page tab to serve your purpose. Apex is a great language in terms of dynamic code and reusability, try to make your code as dynamic as you can depending on your requirement.

Please do comment for any questions, feedback and suggestions. Thanks!!

 

Manish Choudhari

I am a certified Salesforce Application & System Architect and Developer working on Salesforce Technology since 2014. Currently, I have 14 Salesforce certifications along with OCPJP (Oracle Certified Profession JavaSE6 Programmer) working in Salesforce.com Hyderabad as a Technical Engineer. Writing technical blogs, learning new technologies and frameworks and sharing knowledge is my hobby.

This Post Has 2 Comments

  1. Avatar

    Hi, i have a doubt:
    I have to get a list of records from an object when vf is fired in community. How i call the apex method in vf and appear values of the list? Tried your example but not working.
    My code is something like this:

    VF:

    relatedEvents — {!relatedEvents}

    Controller:

    public List relatedEvents {get;set;}

    //@RemoteAction
    public List getRelatedEvents()
    {
    try
    {
    List relatedEvents = new List();
    relatedEvents = [SELECT id,name
    FROM Event__c
    WHERE Event_End_Date__c =: System.today()
    ];
    if(relatedEvents.isEmpty())
    {
    relatedEvents = [SELECT id,name
    FROM Event__c
    WHERE Event_End_Date__c >=: System.today() – 7
    ];
    }
    return relatedEvents;
    }
    catch(Exception e)
    {
    return null;
    }
    }

Leave a Reply

Close Menu