Introduction to Custom Controller
Custom Controller: we use custom controller whenever we want to connect our Visualforce page with any Apex Class for custom logic.
Creating Input Form using Custom Controller:
let us create Input form(where user will fill the value and then save the page) using custom controller in visualforce page. We write the code as shown below which uses MyAccount class as the custom controller and the purpose is to update the value in the 1 field – Account Name as shown below:
<apex:page controller="MyAccout"> <apex:form > <apex:pageBlock > <apex:inputtext value="{!MyAccount.name}"/> <apex:commandButton value="Save" action="{!doSave}"/> </apex:pageBlock> </apex:form> </apex:page>
Apex class code as below: File->New->Apex Class
public class MyAccout { Account act; public MyAccout() { act = [select id, name from account where id = '0012w00000L6oPr']; } public void doSave() { update act; } public Account getMyAccount() { return act; } }
On clicking on preview the page, we get the following output.
In above program we did hard coding where we provide hard coded account Id, which is never recommended in real time application so in the below program, we will let you know how to capture Id at runtime in Apex programming language from visualforce page as well as we develop this class with polymorphic behaviour that means if record exists then it will update the existing record if record does not exists then it will create new record i.e. the reason we used Upsert operation in our class. Please find visualforce page code as below.
<apex:page controller="MyAccout"> <apex:form > <apex:pageBlock > <apex:inputtext value="{!MyAccount.name}"/> <apex:commandButton value="Save" action="{!doSave}"/> </apex:pageBlock> </apex:form> </apex:page>
Apex class code as below: File->New->Apex Class
public class MyAccout { Account act; public MyAccout() { id i = apexpages.currentpage().getparameters().get('id'); if(i == null){ act = new account(); } else { act = [select id, name from account where id =: i ]; } } public void doSave() { upsert act; } public Account getMyAccount() { return act; } }
On clicking on preview the page, we get the following output.
Note: in the above URL in the browser, if you will supply the account record Id in this case it will ask you to update the existing record. If you will not provide the Id into the URL then it will create a new record into the account object.
For updating record use below URL:
https://final-demo-aura-dev-ed–c.visualforce.com/apex/HelloVFPage?id=’0012w00000L6oPr’
else for creating a new record into account object use below URL:
https://final-demo-aura-dev-ed–c.visualforce.com/apex/HelloVFPage