What Is the Difference Between Controllers and Extensions in Visualforce?

What Is the Difference Between Controllers and Extensions in Visualforce?

On February 22, 2025, Posted by , In Salesforce Technical Questions, With Comments Off on What Is the Difference Between Controllers and Extensions in Visualforce?

Question:

Can someone explain the usage of controllers and extensions in Visualforce? When should we use a controller, and in what scenarios should we opt for an extension instead?

Answer:

Salesforce Technical Questions with Answers Apex, LWC, Marketing Cloud

In Visualforce, controllers and extensions define the behavior of a page, dictating how it interacts with Salesforce data and performs user actions. Here’s an explanation of their purposes and scenarios for use:

CRS Info Solutions provides top-notch Salesforce online training for with real-time projects, certification guidance, interview coaching, and a practical, job-ready approach.

A controller is responsible for handling the core logic and data interactions of a Visualforce page. Salesforce provides standard controllers that allow you to perform common operations like querying data, creating records, or performing DML operations without writing any code. However, when you need more advanced or customized functionality, you can use custom controllers to define your own logic.

A custom controller is written in Apex and is used when:

  1. You need to override the default functionality provided by standard controllers.
  2. You want to make new actions (methods) available to the page.
  3. You need to customize the navigation or perform complex operations like HTTP callouts or web services.
  4. You require greater control over how information is accessed or displayed on the page.
  5. You are implementing advanced features such as multi-step wizards or dynamic page behavior.

Example of a Custom Controller:

public class MyCustomController {
    public String greeting { get; set; }

    public MyCustomController() {
        greeting = 'Hello, Visualforce!';
    }

    public void updateGreeting(String newGreeting) {
        greeting = newGreeting;
    }
}

Explanation: The MyCustomController is an Apex controller for a Visualforce page, containing a public string property greeting that is initialized to 'Hello, Visualforce!' in the constructor. The updateGreeting method allows updating greeting with a new value passed as a parameter. This controller can be used in a Visualforce page to display and modify the greeting value dynamically.

Visualforce page using this controller:

<apex:page controller="MyCustomController">
    <h1>{!greeting}</h1>
    <apex:form>
        <apex:inputText value="{!greeting}" />
        <apex:commandButton value="Update Greeting" action="{!updateGreeting}" />
    </apex:form>
</apex:page>

Explanation : The Visualforce page uses MyCustomController to display and update a greeting message. The {!greeting} variable binds to an <apex:inputText>, allowing users to modify its value, which is updated upon clicking the <apex:commandButton> that calls the updateGreeting method in the controller. This setup enables two-way data binding between the page and the Apex controller, facilitating user interaction.

Example of a Controller Extension:

public class MyExtension {
    private final Account acct;

    public MyExtension(ApexPages.StandardController stdController) {
        this.acct = (Account) stdController.getRecord();
    }

    public void updateAccountName(String newName) {
        acct.Name = newName;
        update acct;
    }
}

Explanation : The MyExtension class is an Apex controller extension that works with a StandardController for the Account object. It initializes by casting the standard controller’s record to an Account and provides a method updateAccountName to modify and update the account’s name in the database. This approach allows extending standard Salesforce pages with custom logic while leveraging built-in functionality.

see also: Salesforce training in India

Visualforce Page Example

If you were to use this extension in a Visualforce page, it might look like this:

<apex:page standardController="Account" extensions="MyExtension">
    <h1>Update Account Name</h1>
    <apex:form>
        <apex:inputText value="{!Account.Name}" />
        <apex:commandButton value="Save" action="{!updateAccountName}" />
    </apex:form>
</apex:page>

Explanation : The Visualforce page uses the Account standard controller with the MyExtension Apex extension to update an account’s name. It includes an input field bound to Account.Name and a button that triggers the updateAccountName method in the extension. When clicked, the button submits the form, calling the method to update the account name in the database.

Visualforce page using a standard controller with an extension:

<apex:page standardController="Account" extensions="MyExtension">
    <h1>Update Account Name</h1>
    <apex:form>
        <apex:inputText value="{!Account.Name}" />
        <apex:commandButton value="Save" action="{!updateAccountName}" />
    </apex:form>
</apex:page>

Explanation : The Visualforce page uses the Account standard controller with an Apex extension (MyExtension) to update an account’s name. It includes a form with an apex:inputText bound to Account.Name, allowing users to modify the name, and a commandButton that triggers the updateAccountName method in the extension. This setup enables custom logic execution while leveraging Salesforce’s standard controller functionality.

Summing Up

In Visualforce, controllers manage data and logic, while extensions enhance their functionality. Controllers interact with Salesforce data, with standard controllers handling common objects like Account and custom controllers managing specific business logic. Extensions add custom methods to standard or custom controllers without altering their core behavior, enabling features like calculations, callouts, or navigation tweaks. This combination provides flexibility, allowing developers to extend Visualforce pages while leveraging built-in functionalities.

Advance Your Career with Expert Salesforce Training in India

Take the next step in your career with CRS Info Solutions’ premium Salesforce training, designed to equip you with the skills needed to succeed in the dynamic Salesforce ecosystem. Our expert-led courses cover Salesforce Admin, Developer, and AI modules, providing in-depth knowledge and practical experience through real-world project scenarios.

We focus on practical learning, offering personalized guidance, comprehensive study materials, and thorough certification preparation. Salesforce training in India Our program ensures you’re fully prepared for interviews and equipped to thrive in your Salesforce career. Don’t miss your chance to gain valuable industry insights

join our free demo class today and start your Salesforce journey with confidence! Enroll now for a free demo!!!

Comments are closed.