How to Use Apex Controllers with Visualforce Pages?

In Salesforce, Visualforce is a framework that allows us to build and deploy custom user interfaces on the Salesforce Lightning Platform.

By using the controllers in the Visualforce pages, we can control user interaction, such as data access and component behavior, and also execute complex business logic.

In this Salesforce tutorial, we will learn how to use the Apex controllers with Visualforce Pages in Salesforce.

Controllers in Salesforce Visualforce Pages

A Controller in Visualforce is an Apex class or a set of standard functionalities that manage the interaction between a Visualforce page and Salesforce data.

It handles business logic, processes user input, and performs operations like retrieving, inserting, updating, or deleting records in Salesforce.

There are three types of Visualforce controllers in Salesforce Apex.

  • Standard Controllers
  • Custom Controllers
  • Extensions.

1. Standard Controller: This controller provides out-of-the-box support for specific standard Salesforce objects such as Account and Contact. These standard controllers will utilize the same logic and functionality as standard Visualforce pages, and no additional code is required in Standard Controllers.

Syntax for Standard Controller:

<apex:page standardcontroller =”contact”></apex:page>

2. Custom Controller: The custom controller is used to implement custom business logic and data operations. Custom controllers do not provide default functions, unlike standard controllers.

Syntax for Custom Controller:

<apex : page controller = “Mycontroller”></apex:page>

3. Extension: In a controller, an extension is an apex class that extends the functionality of a standard controller by adding or overriding its logic. Extension controllers begin with a standard controller and are extended or overridden with a custom controller with a custom apex code.

Syntax for extension controller:

<apex:page standardcontroller = “contact” extensions = “Testclass1, Testclass2?></apex:page>

Create a Visualforce Page with a Standard Controller

Now, we will first create a Visualforce page with a controller by following the steps below.

  1. Navigate to the Setup> Visualforce Pages and click the New button.
    • Enter the Name of the custom Visualforce page and select the checkbox Available for Lightning Experience.
Custom visualforce controller in Salesforce
  1. Add the standard controller to the Visualforce page by entering the controller code.
<apex:page standardController="Account">
    <h1>Account Details</h1>
    <apex:form>
        <apex:outputField value="{!Account.Name}" />
        <apex:outputField value="{!Account.Industry}" />
    </apex:form>
</apex:page>

In the above code, the standardController links the Visualforce page to the Account object.

Create a Custom Controller for Visualforce in Salesforce

To create a custom controller, navigate to the Salesforce developer console and follow the steps below.

  1. A custom controller is created within an Apex class; to create an Apex class, navigate File > New >Apex Class.
    • Enter the name of the custom controller and click OK.
Link Controller to visualforce page in Salesforce
  1. Enter the code below for the custom controller.
public class CustomAccountController {
    public Account account { get; set; }

    public CustomAccountController() {
        account = [SELECT Name, Industry FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }

    public void updateAccount() {
        update account;
    }
}
  1. Link the custom controller with the visualforce page.
<apex:page controller="CustomAccountController">
    <h1>Edit Account Details</h1>
    <apex:form>
        <apex:inputField value="{!account.Name}" />
        <apex:inputField value="{!account.Industry}" />
        <apex:commandButton value="Save" action="{!updateAccount}" />
    </apex:form>
</apex:page>
  1. In the above code, the CustomAccountController fetches the Account record and handles updates. The {!updateAccount} trigger invokes the updateAccount method when the button is clicked.
    • After connecting the custom controller to the Visualforce page, save and test the changes in the URL.
https:/< - org url - >.salesforce.com/apex/AccountPage?id=AccountID
Visualforce Controller in Salesforce

Now, we can see the edit option is available on the visualforce page to change the Account name and the Account industry.

Add Functionality to Visualforce page with a Controller Extension

By adding extensions to the Visualforce pages, we can enhance functionality by combining standard and custom controllers. The extension class is also an apex class and can be considered a custom controller.

Execute the code below, which will add a button to the Visualforce page that changes the industry to ‘Technology’ when clicked.

public class AccountExtension {
    private final Account account;

    public AccountExtension(ApexPages.StandardController controller) {
        this.account = (Account)controller.getRecord();
    }

    public void setIndustryToTechnology() {
        account.Industry = 'Technology';
        update account;
    }
}

To link the functionality of the extension controller class, add the extension class to the visualforce page.

<apex:page standardController="Account" extensions="CustomAccountController,AccountExtension">
    <h1>Edit and Update Account Details</h1>
    <apex:form >
        <!-- Display Account Name -->
        <apex:outputLabel value="Account Name:" for="accountName"/>
        <apex:inputField id="accountName" value="{!account.Name}"/>
        
        <!-- Display and Edit Industry -->
        <apex:outputLabel value="Industry:" for="industry"/>
        <apex:inputField id="industry" value="{!account.Industry}"/>
     
        <apex:commandButton value="Save" action="{!updateAccount}"/>
        
        <!-- Update Industry to Technology -->
        <apex:commandButton value="Set Industry to Technology" action="{!setIndustryToTechnology}" style="margin-left:10px;"/>
    </apex:form>
</apex:page>
  • The extension includes both the CustomAccountController and AccountExtension classes.
  • The Set Industry to Technology button calls the setIndustryToTechnology method to update the industry field.
  • The form displays editable fields for the Account name and industry and provides options to save changes or update the sector to “Technology.

After linking the extension controller to the Visualforce page, click the Save button to apply the changes.

Extension controller in Salesforce visualforce

In this way, we can add an extension controller to the Salesforce Visualforce pages.

Conclusion

In this Salesforce tutorial, we have learned how to create a Visualforce page and add a controller to it. In the above example, we have successfully added the Standard, Custom, and Extension controllers to the visualforce page.

By following the above syntax and linking methods of the controllers to the visualforce pages, you can easily create and add controllers to the visualforce pages in your Salesforce org.

You may also like to read:

live webinar

Salesforce Data Cloud with Agentforce Data Library

In this live webinar, we will showcase how Salesforce AI Agents use business data and documents to provide intelligent responses using Agentforce Data Library and Salesforce Data Cloud.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.