Custom Controllers in Visualforce Page
What is a Custom controller? By using custom controllers we can write logic to visualforce pages.
There are three types of controllers available in visualforce. Those are:
- Standard Controllers
- Controllers
- Extensions.
To understand about visualforce controllers go to visualforce controllers
Below example helps you to understand how to write custom controller.
Custom controller is an apex class which is used to implement logic of visualforce page without leveraging the standard functionality.
Syntax to use custom controllers in visualforce page
<apex:page controller="your controller name"> //your vf page code. </apex:page>
Now i will create visualforce page called” insertcollage” collage is a custom object in my org. To enter collage record i am using my own custom save functionality instead of standard save functionality.
Visualforce page code for “insertcollagepage”
<apex:page controller="inserCollage"> <apex:form > <apex:pageBlock title="Collage Details"> <apex:pageblockSection title="Collage Information"> <apex:inputField value="{!coll.collage_name__c}"/> <apex:inputField value="{!coll.collage_id__c}"/> <apex:inputField value="{!coll.collage_phone_number__c}"/> <apex:inputField value="{!coll.adress__c}"/> </apex:pageblockSection> <apex:pageBlockButtons > <apex:commandButton value="Save Collage" action="{!save}"/> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>
Custom controller for above visualforce page
public class inserCollage { public collage__c coll; public void insertCollage() { coll = [select id,college_name__c,college_id__c,college_phone_number__c,adress__c from collage__c where id =: ApexPages.currentPage().getParameters().get('id')]; } public collage__c getcoll() { return coll; } public PageReference save() { upsert coll; PageReference pref = new ApexPages.StandardController(coll).view(); return pref; } }
This is a simple example to under stand to understand custom controllers. In above visualforce i have created a command button called save collage and written logic for that in controller. To under stand this you need basic knowledge about Opps concepts and java.
If you want use standard controller and custom controller at a time then you can go for extension. Below is the syntax to use custom controller.
<apex:page standardController=”standardcontrollername” extensions=”controller name”>
//your vf page code.
</apex:page>