0

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];

2 Answers 2

1

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]
    }
}
1
  • Thanks Sergey :) I did slight changes in your code and it worked for me. Commented Mar 22, 2016 at 6:55
0

Thanks Sergey :)

I did some changes in getContact() as it was showing error System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.AccountId.

I made this getter function like this and it worked.....

// Getting related contacts contact
    public List<Contact> getContacts() {
        List<Contact> aa=[Select AccountId from contact where Id =:cont.Id];
        return [SELECT Contact.AccountId, Name, Id,LastName
                FROM Contact where Id != : cont.Id AND Contact.AccountId= :aa[0].AccountId];
    }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .