Auto populate related lookup fields when one lookup field is selected in visualforce page

By | December 13, 2019

Hi,here we implemented lookup binding scenario. Project object having three lookup objects (Class,Student,Teacher).

Individually, Class object having Student lookup and Student object having Teacher lookup.

Here in Project object we have 3 lookups, if Class lookup field is selected then auto populate Student and Teacher lookup fields.

In Project object, if Student lookup field is selected then auto populate Teacher lookup field.

Apex Class:

public with sharing class RelatedController{
    public Class__c cls {get;set;}
    public Student__c stdt {get;set;}
    
    private ApexPages.StandardController stdCtrl;
    public RelatedController(ApexPages.StandardController std) {
        stdCtrl=std;
    }
    public void PopulateStudentTeacher(){
        Project__c proj=(Project__c) stdCtrl.getRecord();
        if(proj.Class__c == null){return;}
        else{
            cls=[select Name,Student_Lookup__c,Student_Lookup__r.Teacher_Lookup__c from Class__c where Id=:proj.Class__c];
            System.debug('cls'+cls);
            proj.Student__c=cls.Student_Lookup__c;
            proj.Teacher__c = cls.Student_Lookup__r.Teacher_Lookup__c;
        }
    }
    public void PopulateTeacher() {
        Project__c proj=(Project__c) stdCtrl.getRecord();
        if(proj.Student__c == null){return;}
        else{
            stdt=[select Name,Teacher_Lookup__c from Student__c where Id=:proj.Student__c];
            proj.Teacher__c=stdt.Teacher_Lookup__c;
        }
    }
}

VisualForce Page:

<apex:page standardController="Project__c" extensions="RelatedController">
    <apex:form >
        <apex:pageBlock title="Auto Populate Related Objects">
            <apex:pageBlockSection columns="3">
                
                <apex:inputField label="Project Class" value="{!Project__c.Class__c}">        
                    <apex:actionSupport event="onchange" action="{!PopulateStudentTeacher}" rerender="student, teacher"/>
                </apex:inputField>
                <apex:inputField label="Project Student" value="{!Project__c.Student__c}" id="student">
                    <apex:actionSupport event="onchange" action="{!PopulateTeacher}" rerender="teacher"/>
                </apex:inputField>
                <apex:inputField label="Project Teacher" value="{!Project__c.Teacher__c}" id="teacher"/>
                
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:1

Output:2

Leave a Reply

Your email address will not be published. Required fields are marked *