[SalesForce] Populating Related List on Contacts Page using apex

I want to display all the Accounts that have same contacts in them. Suppose Account 'A' has 5 contacts associated to it lets say c1,c2,c3,c4 and c5. Now on contact page i want to see a related list where all other related contacts can be displayed. Means if I open contacts page of c1 then i want a related list showing entries like c2,c3,c4 and c5.

For this I was thinking to use SOQL and then populate the related list using apex. The SOQL query returns all the name of contacts that are related.

List<Contact> acid=[SELECT Id, AccountId, Name, Related_Contacts__c 
                    FROM Contact 
                    WHERE AccountId = : cnt.AccountId];

Best Answer

You have to write a visualforce page for the Contact standard page layout, add it to the layout and write an extension:

Visualforce Page:

<apex:page standardController="Contact" extensions="MyExtension">
    <apex:pageBlock title="{!$ObjectType.Contact.labelPlural}">
        <apex:pageBlockTable value="{!Contacts}" var="cont">
            <apex:column value="{!cont.Name}" />
        </apex:pageBlockTable>
    </apex:pageBlock>
<apex:page>

Controller extension:

public class MyExtension {
    private final Contact cont;

    // Getting the current contact
    public MyExtension(ApexPages.StandardController stdController) {
        this.cont = (Contact)stdController.getRecord();
    }

    // Getting related contacts based on the Account-ID excluding the current contact
    public List<Contact> getContacts() {
        return [SELECT Id, Name, AccountId
                FROM Contact 
                WHERE AccountId = : cont.AccountId)
                AND Id != cont.Id]
    }
}