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 t