In Visualforce, extensions are Apex classes that enhance the functionality of a page's controller. Here's a breakdown of what that means:
1. Controllers in Visualforce
- Standard Controllers: Visualforce pages can use standard controllers, which provide basic functionality for interacting with a single Salesforce object (like Account or Contact). They handle common actions like saving, editing, and deleting records.
- Custom Controllers: For more complex logic, you can create custom controllers in Apex. These classes define all the actions and data handling for your Visualforce page.
2. Why Use Extensions?
- Extend Functionality: Extensions allow you to add new features or modify existing ones in a controller without completely rewriting it.
- Leverage Standard Controllers: You can use an extension to build upon the functionality of a standard controller, overriding specific actions or adding new ones while still benefiting from the standard controller's built-in features.
- Maintain User Permissions: When extending a standard controller, the standard controller's logic runs in user mode, respecting the permissions and field-level security of the current user.
3. How Extensions Work
- Apex Class: An extension is an Apex class that has a constructor which accepts a single argument of type
ApexPages.StandardController
(for extending standard controllers) or the type of your custom controller.
extensions
Attribute: You associate an extension with a Visualforce page using the extensions
attribute of the <apex:page>
tag.
- Accessing Controller Methods: You can reference methods defined in your extension class within your Visualforce markup using {! } notation.
Example :
<apex:page standardController="Account" extensions="MyExtension">
<h1>Account Name: {!account.Name}</h1>
<apex:form>
<apex:inputField value="{!account.Name}"/>
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Custom Action" action="{!myCustomAction}"/>
</apex:form>
</apex:page>
public class MyExtension {
private Account acc;
public MyExtension(ApexPages.StandardController stdController) {
this.acc = (Account)stdController.getRecord();
}
public PageReference myCustomAction() {
// Perform some custom logic here
return null;
}
}
In this example, MyExtension
extends the standard Account
controller. It adds a new action myCustomAction
while still allowing the page to use the standard save
action.
Key Benefits of Extensions :
- Code Reusability: You can reuse extension classes across multiple Visualforce pages.
- Organization: Extensions help keep your controller logic organized and modular.
- Maintainability: It's easier to maintain and update code when it's separated into logical units.