Call Us Today !

How to use custom controller in Salesforce

Controllers are used to retrieve data that will be displayed in your Visualforce page. They usually contain code that will be executed depending on the page actions performed by users such as a button getting clicked.

Functions of Custom Controllers

Other than displaying data, they can also be used to insert data, validate data, or even callout to an external web service. You can think of custom controllers as a way to take control of the logic of your custom app.

Using Custom Controllers

Reference the name of the controller class to add a custom controller to a page on Visualforce. You will reference the name on the controller attribute <apex:page>

Open your developer console and go to File > New > Visualforce Page. You will also need to replace the markups in the editor with the following bit of code:

<apex:page controller= »ContactsListController »>
<apex:pageBlock title= »Contacts List » id= »contacts_list »>

<!– Contacts List goes here –>


Don’t save that yet since you still need to create your apex class called ContactsListController.
Create a new apex class in the developer console by going to File > New > Apex Class. For the class name use ContactsListController.

Use the following code as a replacement:

public class ContactsListController {
// Controller code goes here

Go back to your Visualforce page and save it. Notice that the error goes away.
At this point, these two codes do nothing other than act as placeholders. The primary purpose of a lot of controllers is to do data updates, display data, or retrieve data.

For instance, you want your custom controller to retrieve data. Go back to your apex class code and replace the comment with the following simple code for data retrieval:

private String sortOrder = ‘LastName’;

public List<Contact> getContacts() {

List<Contact> results = Database.query(
‘SELECT Id, FirstName, LastName, Title, Email ‘ +
‘FROM Contact ‘ +
‘ORDER BY ‘ + sortOrder + ‘ ASC ‘ +
‘LIMIT 10’
return results;

Other than data retrieval you can add new action methods.

Share this article!

Partager sur facebook
Partager sur twitter
Partager sur linkedin
Partager sur email