SAVE UP to ₹4999/- OFF On All Salesforce Courses Claim Offer

15

Controller Extensions Part 2

Here’s a sample code example for a Visualforce page with a standard controller and multiple controller extensions in Apex:

Visualforce Page (samplePage.page):

<apex:page controller="Account" extensions="SampleExtension1, SampleExtension2">
    <h1>Welcome to the Sample Page</h1>
    
    <apex:outputText value="Account Name: {!accountName}" />
    <apex:outputText value="Contact Name: {!contactName}" />
</apex:page>

Controller (SampleController.cls):

public class SampleController {
    public String accountName { get; set; }
    
    public SampleController() {
        // Initialization logic
        accountName = 'ABC Company';
    }
}

Controller Extension 1 (SampleExtension1.cls):

public class SampleExtension1 {
    private ApexPages.StandardController stdController;
    
    public SampleExtension1(ApexPages.StandardController controller) {
        stdController = controller;
    }
    
    public String getAccountName() {
        // Accessing the standard controller's record
        Account acc = (Account)stdController.getRecord();
        return acc.Name;
    }
}

Controller Extension 2 (SampleExtension2.cls):

public class SampleExtension2 {
    private ApexPages.StandardController stdController;
    
    public SampleExtension2(ApexPages.StandardController controller) {
        stdController = controller;
    }
    
    public String getContactName() {
        // Accessing the standard controller's record
        Contact con = (Contact)stdController.getRecord();
        return con.Name;
    }
}
Salesforce Developer
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Book A 15-Minutes Free Career Counselling Today!