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:form>
<apex:pageBlock title=”Contacts List” id=”contacts_list”>

<!– Contacts List goes here –>

</apex:pageBlock>
</apex:form>
</apex:page>

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.

Leave a Reply

Close Menu