What Are Controllers and Extensions in Visualforce?

Question
Explain the usage of controllers and extensions in Visualforce, and in which scenarios should each be used?
Answer
In Visualforce, controllers and extensions are both used to manage the logic of your page, but they serve distinct roles and have different characteristics. Understanding the difference is crucial to using them effectively in your Salesforce applications.
Controllers are Apex classes that are associated with a Visualforce page to provide the page with the necessary logic and data. They are the backbone of any Visualforce page because they allow interaction with Salesforce objects and data. There are three main types of controllers in Visualforce:
Standard Controllers: These are automatically provided by Salesforce for standard objects like Account, Contact, and Case. A standard controller gives you the ability to perform actions such as save, delete, and edit records without needing to write custom logic for these operations. For example, to display an Account record with standard functionality, you would use the following syntax in your Visualforce page:
<apex:page standardController="Account">
<!-- Visualforce page content here -->
</apex:page>
Standard List Controllers: If you need to work with a list of records, such as displaying multiple Accounts, you would use a standard list controller. This controller provides the necessary functionality for paging, filtering, and selecting records. Here’s an example:
<apex:page standardController="Account" recordsetVar="accountsList">
<!-- Visualforce page content to display accountsList here -->
</apex:page>
Custom Controllers: When you need complete control over the functionality of the page and want to implement custom logic, you can create your own Apex controller. For example, if you need to perform a complex query or implement specific logic beyond what the standard controllers provide, you would use a custom controller:
<apex:page controller="MyApexClass">
<!-- Visualforce page content here -->
</apex:page>
A custom controller allows you to define methods that you can call within the page, giving you full control over the behavior of the page. If you want to leverage the built-in standard controller functionality (e.g., saving a record), you can instantiate it in your custom controller, as shown below:
public with sharing class MyApexClass {
private ApexPages.StandardController ctrl;
public Account acct {get; set;}
public MyApexClass() {
try {
acct = [SELECT Name FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
} catch (QueryException e) {
acct = new Account();
}
ctrl = new ApexPages.StandardController(acct);
}
public PageReference save() {
// Call the save method of the standard controller
return ctrl.save();
}
}
Extensions are additional classes that extend the functionality of a controller (whether standard or custom). Extensions cannot function independently and must always be used in conjunction with a controller. They allow you to add custom logic to an existing controller without modifying the original controller class. This is useful when you want to enhance the behavior of standard controllers but still want to retain their built-in functionality.
You can use an extension by specifying it alongside the standard or custom controller in your Visualforce page. For example:
<apex:page standardController="Account" extensions="MyExtensionClass">
<!-- Visualforce page content here -->
</apex:page>
An extension class must have a constructor that accepts the controller object as a parameter. This allows the extension to access the controller’s methods and properties. Here’s an example of an extension that adds custom functionality to a standard controller:
public with sharing class MyExtensionClass {
private ApexPages.StandardController ctrl;
public Account acct {get; set;}
public MyExtensionClass(ApexPages.StandardController controllerParam) {
ctrl = controllerParam;
acct = (Account) ctrl.getRecord();
}
public PageReference customSave() {
// Override or add custom functionality to the save process
return ctrl.save();
}
}
You can also use extensions with custom controllers, as shown below:
<apex:page controller="MyApexClass" extensions="MyExtensionClass">
<!-- Visualforce page content here -->
</apex:page>
In this case, the extension class would interact with your custom controller to extend its functionality:
public with sharing class MyExtensionClass {
private MyApexClass ctrl;
public MyExtensionClass(MyApexClass controllerParam) {
ctrl = controllerParam;
}
// Custom methods for extending the controller
}
In summary, controllers provide the core functionality for your Visualforce pages, managing data and handling actions, while extensions enhance the capabilities of controllers by adding custom logic. A page can only have one controller, but you can add multiple extensions to a page, allowing for flexible and modular design.
Enroll for Career-Building Salesforce Training with Real-Time Projects
Our Salesforce Course is meticulously designed to offer an in-depth understanding of the Salesforce platform, providing you with the crucial skills needed to excel in the CRM domain. The program includes essential modules like Salesforce Admin, Developer, and AI, integrating foundational theory with practical, hands-on experience. By engaging in live projects and real-world assignments, you’ll develop the expertise to solve complex business challenges with confidence, using Salesforce solutions. Our experienced instructors ensure you acquire both technical knowledge and valuable industry insights, enabling you to thrive in the Salesforce ecosystem.
In addition to mastering technical concepts, our Salesforce Training in Thiruvananthapuram offers personalized mentorship, exam preparation, and interview coaching to boost your career prospects. You’ll have access to comprehensive study materials, practical project experience, and consistent support throughout your learning journey. Upon completion, you’ll be fully prepared for certification exams and equipped with the practical problem-solving skills employers highly value. Embark on your Salesforce career with us—Sign up for a Free Demo today!