Tag Archives: Child Record

Retrieve Parent Record From Child Record in Salesforce

In below example “Project” is the custom Child object, and “Student” is the custom Master object.

Controller:

public class SampleController
{
    //Contact List Variable
    public List<Project__c> proList {get;set;}
    
    //Constructor
    public SampleController(){
        proList = [SELECT Id, Name, Student__r.Name FROM Project__c LIMIT 10];
    }    
}

Visualforce Page:

<apex:page controller="SampleController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!proList}" var="pro">
                <apex:column value="{!pro.Name}"/>
                <apex:column value="{!pro.Student__r.Name}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

Retrieve Child Record From Parent Record in Salesforce

In below example “Student” is the custom Master object, and “Project” is the custom Child object.

Controller:

public class SampleController
{
    //Contact List Variable
    public List<Student__c> stuList {get;set;}
    
    //Constructor
    public SampleController(){
        stuList = [SELECT Id, Name, (SELECT Id, Name FROM Projects__r) FROM Student__c LIMIT 10];
    }    
}

Visualforce Page:

<apex:page controller="SampleController">
    <table>
        <apex:repeat value="{!stuList}" var="stu">
            <tr>
                <td><apex:outputText value="{!stu.Name}"/></td>
                <apex:repeat value="{!stu.Projects__r}" var="pro">
                    <td><apex:outputText value="{!pro.Name}"/></td>
                </apex:repeat>
            </tr>
        </apex:repeat>
    </table>
</apex:page>