Custom Related List Using Visualforce and Apex

Salesforce provides a standard related list for the child objects to be displayed in the detail page of the parent records. Visualforce pages can be used with standard controller and extensions to create a custom related list by customizing with Apex.

Salesforce related list for the child objects to be displayed in the detail page of the parent records. Visualforce pages can be used with standard controller and extensions to create a custom related list by customizing with Apex.

The example below shows how to create a custom related list using Visualforce page with a standard controller and extension for the account object to show the related contact records.

Step 1: Create a Visualforce Page

ContactRelatedList.vfp 

<apex:page standardController="Account" extensions="ContactRelatedListController" sidebar="true" showHeader="false" >     

    <apex:form >                 

        <apex:pageblock id="ContactList"> 

          <div style="margin-left: 30%;"><apex:commandLink value="New Contact" action="{!newContact}" target="_parent" styleClass="btn" style="text-decoration:none;padding:4px;"/></div> 

            <br/> 

            <apex:pageBlockTable value="{!contacts}" var="cont" rendered="{!NOT(ISNULL(contacts))}">                 

                <apex:column HeaderValue="Action" width="60"> 

                    <apex:commandLink value="Edit" style="color:#015ba7;" action="{!editContact}" target="_parent" ><apex:param value="{!cont.id}" name="contactId"/> 

                    </apex:commandLink> 

                    &nbsp;|&nbsp; 

                    <apex:commandLink value="Del" onclick="return confirm('Are you sure?')" style="color:#015ba7;" action="{!deleteContact}" target="_parent"><apex:param value="{!cont.id}" name="contactId"/> 

                    </apex:commandLink> 

                </apex:column> 

                <apex:column headerValue="Contact Name"><apex:outputLink value="/{!cont.id}" target="_blank">{!cont.Name}</apex:outputLink> </apex:column>               

                <apex:column value="{!cont.region__c}"/> 

                <apex:column value="{!cont.MobilePhone}"></apex:column> 

                <apex:column value="{!cont.Email}"/>              

            </apex:pageBlockTable>            

            <apex:outputLabel value="No records to display" rendered="{!(ISNULL(contacts))}" styleClass="noRowsHeader"></apex:outputLabel> 

        </apex:pageblock> 

    </apex:form>  

</apex:page>

This Visualforce page uses the account standard controller and the controller extension to display the records as a related list.

Step 2: Create a controller extension   

ContactRelatedListController.apxc 

public class ContactRelatedListController {     

    public List<contact> contacts{get;set;} 

    public Account accounts {get;set;} 

    public Account acc {get;set;} 

     

    //Constructor 

    public ContactRelatedListController(ApexPages.
StandardController controller) { 

        acc = (account)controller.getRecord();      

        accounts = [SELECT id FROM account WHERE id=: acc.id LIMIT 1]; 

        contacts = [SELECT id,region__c,Name, mobilephone, email FROM contact WHERE accountid = :accounts.id ORDER BY Name];     

} 

    //This method is to create a new contact while clicking on the Add contact button 

    public pageReference newContact(){  

 pageReference pageRef = new pageReference(URL.getSalesforceBaseUrl().
toExternalForm() + '/003/e?&retURL=' + accounts.id);  

        return pageRef; 

    } 

    //This method is to edit the existing contact record while clicking the Edit link 

    public pageReference editContact(){  

 String contactId = Apexpages.currentpage().getParameters().
get('contactId');  

 pageReference pageRef = new pageReference(URL.getSalesforceBaseUrl().
toExternalForm() + '/' + contactId + '/e?retURL=' + accounts.id);  

        return pageRef;  

    }    


 //This method is to delete the contact record while clicking the Del link 

    public pageReference deleteContact(){  

   String contactId = Apexpages.currentpage().getParameters().
get('contactId');  

        contact contactList = [SELECT Id FROM contact WHERE id = : contactId LIMIT 1]; 

        delete contactList; 

        String baseUrl = URL.getSalesforceBaseUrl().
toExternalForm(); 

        PageReference redirectPage = new PageReference(baseUrl+'/'+accounts.id); 

        return redirectPage;  

    }   

}

The controller extension gets the parameter while clicking on the action links like edit and delete and uses it for editing the existing contact records and deleting it.

Step 3: Create a section in Account layout 

To create a new section, edit the account layout and drag and drop the new section to the layout,select the 
Visualforce page ContactRelatedList and add it to the section.Select an account record to view thecustom related list of contact records related to the account.

The screenshot above is the standard related list that displays the list of child contacts for an account.

The image above is the custom related list that uses Visualforce page on the account layout and it displays the list of child contacts for an account –similar to the standard related list. By clicking the Edit link, the existing records can be modified, and by clicking on the Del link the records can be deleted, and by clicking on the New Contact button, a new contact record can be created.

The Visualforce page passes the id as the parameter to the controller extension where it was customized to modify, create and delete the records.

Reference Link: 

1.https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm

2.https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_intro.htm

About MST

At MST Solutions our cornerstone is to adapt, engage and create solutions which guarantee the success of our clients. The talent of our team and experiences in varied business verticals gives us an advantage over other competitors.

Recent Articles

How to improve the performance of Visualforce Page

Whenever possible, try to use the declarative or standard feature such as Approval Processes, Visual Flows, and Workflows because these components are already fully optimized by the Force.com; therefore, it won’t count against most of the governor limits but in some cases business may need complex logic; then we can go for the programmatic features.

Read Article »

Work with us.

Our people aren’t just employees, they are key to the success of our business. We recognize the strengths of each individual and allow them time and resources to further develop those skills, crafting a culture of leaders who are passionate about where they are going within our organization.