The Controllers And Extensions

Print   

02 Nov 2017

Disclaimer:
This essay has been written and submitted by students and is not an example of our work. Please click this link to view samples of our professional work witten by our professional essay writers. Any opinions, findings, conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of EssayCompany.

A set of instructions that can react with the user interaction of Visualforce markup (like button click or link click) is called a controller. A controller can control the behavior of a page and that can be used to access the data which should display in the page.

This chapter will introduce you to few types of controllers and extensions which can be used for Visualforce pages. We will understand the controller types with examples.

The agenda for this chapter is as follows:

Standard controllers

Standard List Controllers

Custom Controllers & Controller Extensions

Working with Large Sets of Data on Visualforce page

Order of execution of a Visualforce page

Validation Rules and Standard Controllers / Custom Controllers

Using the transient Keyword

Considerations for Creating Custom Controllers and Controller Extensions

Let's get closer to controllers & extensions…..

This chapter includes a set of examples to explain important elements and features of Visualforce. Starting from this chapter we will build an Order Processing application. There are four custom objects (API Names : Customer__c, Item__c, Order__c, Order_Line__c) in this application. Following is the E-R diagram of Order processing application whish is going to build on Force.com platform.

9818_02_01.png

Standard Controllers

The Force.com platform provides few types of controllers. First one is Standard controllers and every sObject has a standard controller. They have the same logic and functionalities as they originally used in standard pages. Therefore we can use standard controllers with Visualforce pages. For a example, if we use Contact standard controller for a Visualforce page, we can implement the standard Save method for Contact without writing any additional Apex codes. That behaviour is same as the Save on standard Contact edit page.

How to use a Standard controller with Visualforce page

The <apex:page> tag has a attribute called standardController which is use to associate a Standard controller with a Visualforce Page. Value of the standardController attribute would be the API name of a sObject.

<apex:page standardController="Customer__c">

</apex:page>

Above code is show the usage of standardController attribute.

Note : You cannot use standardController and controller attributes at the same time.

Standard Controller Actions

In Visualforce pages, we can define action attribute in following standard visualforce components.

<apex:commandButton> - creates a button that calls an action

<apex:commandLink> - creates a link that calls an action

<apex:actionPoller> - periodically calls an action

<apex:actionSupport> - makes an event (such as "onclick", "onmouseover", and so on) on another, named component, call an action

<apex:actionFunction> - defines a new JavaScript function that calls an action

<apex:page> - calls an action when the page is loaded

An action method can be called from the page using the {!} notation. For a example, if your action methods name is "MyFirstMethod", then the you can use {!MyFirstMethod} notation for calling the action method from the page markup.

Note : This action method can be from standard controller or custom controller or controller extension.

A standard controller has few standard action methods as follows;

save – Insert / update a record. Upon successful completion it will be redirected to the standard detail page or custom Visualforce page.

quicksave – Insert / update a record. There is no any redirection to a detail page or a custom Visualforce page.

edit – Navigates the user to the edit page with current record. Upon successful completion it will be returned to the page which invoked the action.

delete – Delete the current record. Redirect to the list view page with selecting most recently viewed list filter.

cancel – Cancels an edit operation. Upon successful completion it will be returned to the page which invoked the edit action.

list - Redirect to the list view page with selecting most recently viewed list filter.

For example, the following page allows us to insert a new customer or update a customer record. If we are going to use this page for updating a customer record, then the URL must be specified with the id query string parameter. Every standard controller has a getter method that returns the record specified by the id query string parameter in the page URL. When we click Save, the save action is triggered on the standard controller, and the customer is updated. If we are going to use this page to inserting a customer record, then the URL must not be specified with the id query string parameter. In this scenario, when we click the Save, the save action is triggered on the standard controller, and a new customer record is inserted.

<apex:page standardController="Customer__c">

<apex:form >

<apex:pageBlock title="New Customer" mode="edit">

<apex:pageBlockButtons >

<apex:commandButton action="{!save}" value="Save"/>

</apex:pageBlockButtons>

<apex:pageBlockSection title="My Content Section" columns="2">

<apex:inputField value="{!Customer__c.Name}"/>

<apex:inputField value="{!Customer__c.Email__c}"/>

<apex:inputField value="{!Customer__c.Address__c}"/>

<apex:inputField value="{!Customer__c.Telephone__c}"/>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:form>

</apex:page>

Note: The page markup allows you to access fields of a particular sObject using {!sObjectAPIName.FieldAPIName}. For example, if you want to access the Email field of Customer object, the page that uses the Customer__c standard controller can use {!Customer__c.Email__c} to return the value of Email field on the Customer which is in current context.

The following page allows us to view a customer record. In this page also, the URL must be specified the id query string parameter. The getter method of Customer__c standard controller returns the record specified by the id query string parameter in the page URL.

<apex:page standardController="Customer__c">

<apex:form >

<apex:pageBlock title="Customer" mode="edit">

<apex:pageBlockButtons >

<apex:commandButton action="{!save}" value="Save"/>

</apex:pageBlockButtons>

<apex:pageBlockSection title="Customer Details" columns="2">

<apex:outputField value="{!Customer__c.Name}"/>

<apex:outputField value="{!Customer__c.Email__c}"/>

<apex:outputField value="{!Customer__c.Address__c}"/>

<apex:outputField value="{!Customer__c.Telephone__c}"/>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:form>

</apex:page>

Note: To check the accessibility of particular object for the logged user, you can use {!$ObjectType.objectname.accessible} notation. This expression returns a Boolean value. For a example, if you want to check the accessibility of the Customer object, you can use {!$ObjectType.Customer__c.accessible}.

Standard List Controllers

Second controller type is Standard List Controller which can be used for displaying or performing a action on a set of records (including related lists, list pages and mass action pages). It allows us to filter records in particular page. We can use Standard list controllers for Account, Asset, Campaign, Case, Contact, Contract, Idea, Lead, Opportunity, Order, Product2, Solution, User, and all the Custom objects.

How to use Standard List Controller with Visualforce

Similar to standard controller, we can specify the standardController attribute of <apex:page> component. Additionally, we need to specify the recordSetVar attribute of <apex:page> component.

Note: The standardController attribute specifies the type of records that we want to access. The recordSetVar attribute indicates that the page uses a list controller and the variable name (used to access data in the record collection) of the record collection.

Following markup explains how the page can access list of records when the page is associated with a list controller. In the following example, you can refer list of customer records. Figure 2.2 illustrates the result of following page.

<apex:page standardController="Customer__c" recordSetVar="customers" sidebar="false">

<apex:pageBlock >

<apex:pageBlockTable value="{!customers}" var="a">

<apex:column value="{!a.name}"/>

</apex:pageBlockTable>

</apex:pageBlock>

</apex:page>

9818_02_02.png

Standard List Controller Actions

All the standard visualforce components which have the action attribute can be used with a visualforce page with standard list controller. The usage of those components is same as standard controller. Following action methods are supported by all standard list controllers.

save – Insert / update a record. Upon successful completion it will be redirected to the standard detail page or custom visualforce page.

quicksave – Insert / update a record. There is no any redirection to a detail page or custom visualforce page.

List – Redirect to the list view page with selecting most recently viewed list filter when the filterid is not specified by the user.

cancel –. Cancels an edit operation. Upon successful completion it will be returned to the page which invoked the edit action.

first - Displays the first page of records in the set.

last - Displays the last page of records in the set.

next - Displays the next page of records in the set.

previous - Displays the previous page of records in the set.

List views in salesforce standard pages can be used for filtering records which displayed on the page. For example, on the customer home page, you can select "start with c" view from the list view drop down and view customers whose name is start with letter "c". You can implement that functionality on a page associated with a list controller.

Pagination can be added to a page associated with a list controller. The pagination feature allows you to implement the next and previous actions.

For example, to create a simple list of customers with a list view and pagination, create a page with the following mark-up:

<apex:page standardController="Customer__c" recordSetvar="customers">

<apex:form id="theForm">

<apex:pageBlock title="Viewing Customers">

<apex:pageBlockSection >

<apex:selectList value="{!filterid}" size="1">

<apex:selectOptions value="{!listviewoptions}"/>

<apex:actionSupport event="onchange" rerender="list"/>

</apex:selectList>

</apex:pageBlockSection>

<apex:pageBlockSection id="list">

<apex:dataList var="a" value="{!customers}" type="1">

{!a.name}

</apex:dataList>

</apex:pageBlockSection>

<apex:panelGrid columns="2">

<apex:commandLink action="{!previous}" rerender="list">Previous</apex:commandlink>

<apex:commandLink action="{!next}" rerender="list">Next</apex:commandlink>

</apex:panelGrid>

</apex:pageBlock>

</apex:form>

</apex:page>

9818_02_02.png

Custom Controllers & Controller Extension

Custom Controllers and Controller extension are written using Apex..

What is a Custom Controller?

Custom Controllers are used to implement logics & functionalities without using a standard controller. Use custom controllers when you want to;

Implement completely different functionality and don’t need rely on standard controller behaviour.

Override existing functionalities

Make new actions for the page

Customize the navigation

Use HTTP callouts or web services

Use a wizards

Have greater control of information access on the page

Run your page without applying permission

Note : A page is allowed for only one controller.

Building a Custom Controller

You can build a custom controller in two ways.

Via setup page – Your Name  Setup  Develop  Apex Classes  New

Via Visualforce editor – After creating the page you can specify the custom controller name in controller attribute on <apex:page> tag and hit the Save button. Then, if you are a developer user, the page will be asking you to create the class with the name you entered. Then the newly created controller will be showed on the Visualforce editor. See figure 2.4

Note: You have the choice to write controller classes with sharing or without sharing keyword which is influence to run the particular page in system mode or user mode.

9818_02_04.png

Following class is an example of custom controllers. This custom controller has the functionalities for retrieving existing item list from Item__c custom object and adding a new item record. insertNewItem is the action method of ItemController. ExistingITems is a list of Item property which is used to retrieve existing item records. ExistingITems property has an override get method.

public with sharing class ItemController {

//public item property for new insertion

public Item__c NewItem{get;set;}

public ItemController(){

NewItem = new Item__c();

}

//get existing items to show in a table

public List<Item__c> ExistingITems{

get{

ExistingITems = new List<Item__c>();

ExistingITems = [SELECT Id, Name, Item_Name__c, Unit_Price__c FROM Item__c LIMIT 100];

return ExistingITems;

}

set;

}

public PageReference insertNewItem() {

try{

insert NewItem;

//reset public property for new insert

NewItem = new Item__c();

}catch(DmlException ex){

ApexPages.addMessages(ex);

}

return null;

}

}

Note: A Custom controller uses no-argument constructor. You cannot create a constructor that includes parameters for a custom controller.

Above controller is associated with the following Visualforce page. This page has two <apex:pageBlock> components. One for display the existing item records table and other is for inserting new items.

<apex:page controller="ItemController">

<apex:form >

<apex:pageBlock title="Existing Items">

<apex:pageBlockTable value="{!ExistingITems}" var="oneItem" rendered="{!ExistingITems.size > 0}">

<apex:column value="{!oneItem.Item_Name__c}"/>

<apex:column value="{!oneItem.Unit_Price__c}"/>

</apex:pageBlockTable>

<apex:outputText value="No records to display" rendered="{!ExistingITems.size == 0}"></apex:outputText>

</apex:pageBlock>

<apex:pageBlock title="New Item">

<apex:pageMessages ></apex:pageMessages>

<apex:pageBlockSection >

<apex:inputField value="{!NewItem.Item_Name__c}"/>

<apex:inputField value="{!NewItem.Unit_Price__c}"/>

</apex:pageBlockSection>

<apex:pageBlockButtons >

<apex:commandButton action="{!insertNewItem}" value="save"/>

</apex:pageBlockButtons>

</apex:pageBlock>

</apex:form>

</apex:page>

What is Controller Extension?

Controller Extensions are used to extend the logics & functionalities of a standard controller or a custom controller. A controller extension cannot be on a page without a standard controller or a custom controller. Use controller extensions when you want to;

Keep majority of functionalities of a standard or custom controller as it is and add more functionalities.

Build a Visualforce page which shoud run according to the user permissions.

Building a Controller Extension

We can build a controller extension using ways that used to build the custom controller.

Note: An extensions cannot live by themselves on a page. It can be used on a Visualforce page with a custom controller or a standard controller.

The following class is a simple example of a controller extension. This controller extension is used to extend the logics & functionalities of the Order__c custom object’s standard controller. In this extension, we have a single argument constructor to fetch the order record from the standard controller. getRecord() is the method for fetching record from standard controller. prepareFullOrder() method is a custom method that implemented for query the order lines of particular order.

public with sharing class OrderViewExtension{

public Order__c CurrentOrder{get;set;}

public List<Order_Line__c> OrderLines{get;set;}

public OrderViewExtension(ApexPages.StandardController controller){

CurrentOrder = new Order__c();

this.CurrentOrder = (Order__c)controller.getRecord();

prepareFullOrder();

}

public void prepareFullOrder(){

OrderLines = new List<Order_Line__c>();

OrderLines = [SELECT Id, Name, Price__c, Item__c, Item__r.Unit_Price__c,Item__r.Item_Name__c, Order__c, Quantity__c FROM Order_Line__c WHERE Order__c =: this.CurrentOrder.Id];

}

}

Note: A controller extension uses one-argument constructor with the argument type of ApexPages.StandardController or a custom controller type.

Following Visualforce page uses the above controller extension. On the page, we have page block with two sections. First section is shown us order header details. Second section is there to show the order lines of a particular order.

<apex:page standardController="Order__c" extensions="OrderViewExtension">

<apex:form >

<apex:pageBlock >

<apex:pageBlockSection title="Order Header">

<apex:outputField value="{!Order__c.Name}"/>

<apex:outputField value="{!Order__c.Customer__c}"/>

<apex:outputField value="{!Order__c.Planned_Delivery_Date__c}"/>

</apex:pageBlockSection>

<apex:pageBlockSection title="Order Lines" columns="1">

<apex:pageBlockTable value="{!OrderLines}" var="line">

<apex:column value="{!line.Name}"/>

<apex:column headerValue="Item">

<apex:outputLink value="/{!line.Item__c}" target="_blank">{!line.Item__r.Item_Name__c}</apex:outputLink>

</apex:column>

<apex:column value="{!line.Item__r.Unit_Price__c}"/>

<apex:column value="{!line.Quantity__c}"/>

<apex:column value="{!line.Price__c}"/>

</apex:pageBlockTable>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:form>

</apex:page>

Controller Methods

There are three types of methods which can be used within a custom controller or a controller extension.

Getter methods

Setter methods

Action Methods

Getter methods

Developers can use getter methods to display database or other computed values in Visualforce markup. That means, getter methods are used to pass data from Apex controllers to Visualforce page . There are two ways to define getter methods.

Typically, getter methods are named as getVariable, where the variable is the name of the attribute which returns from the getter method.

public class GetterSetterExample{

String GetterVariable;

public String getGetterVariable() {

return GetterVariable;

}

}

A getter method can define the attribute with default getter and setter methods.

public class GetterSetterExample{

public String GetterVariableDefault{get;set;}

}

The variable can be accessed on Visualforce page with the {!} expression.

Setter Methods

Setter methods are used to pass user defined values to the Apex controller. Setter methods are defined in the same way as getter methods were defined. Following example uses default getter and setter methods for searching items which are already in the database.

public with sharing class SearchItemController {

public List<Item__c> ExistingItems{get;set;}

public String Keyword{get;set;}

public SearchItemController(){

ExistingItems = new List<Item__c>();

}

public void SearchItems(){

ExistingItems = [SELECT Id, Name, Item_Name__c, Unit_Price__c FROM Item__c WHERE Item_Name__c LIKE: ('%'+Keyword+'%')];

}

}

Following is the Visualforce page which uses the above controller. Keyword attribute has the default getter and the setter methods for <apex:inputText> component which is used to acquire the user’s input. ExistingItems list attribute also has the default getter and the setter methods for searching and displaying the search result. When the user enters a keyword to search and clicks the Search button, SearchItems() action method will be executed and it acquired the keyword search text and run the query for search items. . Before the action method executes, Keyword setter method will be executed. Then the query result will be collected to the ExistingItems list attribute and ExistingItems getter method will be executed. The page will display the search result.

<apex:page controller="SearchItemController">

<apex:form >

<apex:pageBlock >

<apex:pageBlockSection >

<apex:pageBlockSectionItem >

<apex:outputLabel value="Item Name Or keyword"></apex:outputLabel>

<apex:inputText value="{!Keyword}"/>

</apex:pageBlockSectionItem>

<apex:commandButton value="Search" action="{!SearchItems}"/>

</apex:pageBlockSection>

</apex:pageBlock>

<apex:pageBlock title="Search Result" id="searchResult">

<apex:pageBlockTable value="{!ExistingItems}" var="oneItem" rendered="{!ExistingItems.size > 0}">

<apex:column value="{!oneItem.Item_Name__c}"/>

<apex:column value="{!oneItem.Unit_Price__c}"/>

</apex:pageBlockTable>

<apex:outputText value="No records to display" rendered="{!ExistingItems.size == 0}"></apex:outputText>

</apex:pageBlock>

</apex:form>

</apex:page>

Action Methods

Action methods are used to implement our custom or extended logics and functionalities in a custom controller or a controller extension. Action methods can be triggered on page events such as button click or JavaScript events. In Visualforce pages, we can define the action attribute in many standard visualforce components. The components are <apex:commandButton> , <apex:commandLink> , <apex:actionPoller>, <apex:actionSupport> , <apex:actionFunction> ,and <apex:page> . Above item search example has an action method called SearchItems. SearchItems. It is used to query items according to the user input given for item search.

Working with Large Sets of Data on Visualforce page

On a Visualforce page, we have to work with single record as well as large sets of data. When we work with large sets of data, we may use iteration components like <apex:pageBlockTable>, <apex:repeat> , <apex:dataTable>. These iteration components are limited to a maximum of 1000 items in a collection. Refer the search item example for the usage of iteration component. We have used <apex:pageBlockTable> in above search item example.

Note: Custom controllers and controller extensions are adhere to Apex governor limits.

Visualforce provides "read only mode" feature to overcome the limit on number of rows which can be queried within one request and the limit on number of collection items which can be iterated on the page. There are two ways to set up the Visualforce read only mode.

Setting Read-Only Mode for Controller Methods – For this setting, We can define Visualforce controller methods with @ReadOnly annotation. This read only mode relaxes the number of records queried within one query from 50000 to 1 million rows. @ReadOnly annotation based read only mode is used in JavaScript remoting as the target of remote JavaScript call to load data set for <apex:chart> component and displays some value in a component.

Setting Read-Only Mode for an Entire Page – This read only mode can be enabled by adding true value for the readOnly attribute which is on <apex:page>. This read only mode relaxes the number of records queried within one query from 50000 to 1 million. It also increases the maximum number of items in a collection for an iteration components. Since this is a read only mode, you have to note that the page cannot execute any DML operation.

Order of execution of a Visualforce page

A Visualforce page has a life cycle that is the life timebetween the page is created and destroyed during the user session. The life cycle is defined by the type of Visuaforce page request and the content of the page. There are two types of Visualforce page requests.

Get request

Postback request

Order of Execution for Visualforce Page Get Requests

When we request a new page by entering a URL or by clicking button or a link, a get request is created. In the following diagram, it illustrates how a Visualforce page interacts with a custom controller or a controller extension during a get request.

9818_02_05.png

Constructor methods are called by initiating the controller objects

If there are any custom components, they are created and constructor methods are called on associated class. If any attribute is specified in a component using an expression, expressions are also evaluated.

Then executes any assignTo attributes, then expressions are evaluated. After that, the action attribute on the <apex:page> is evaluated and all the getter or setter are called.

If the page contains an <apex:form> tag, all the information represents the state of the database is encrypted and saved in the view state between page requests. Whenever the page is updated, that view state is also updated.

Send the result HTML to the browser. If there are any client side technologies (such as JavaScript, CSS) , the browser executes them.

Order of Execution for Visualforce Page Postback Requests

Some user interactions (eg:- a save action triggered by user user’s button click) require page updates, typically those page updates are performed by postback requests. Following diagram illustrates how a Visualforce page interacts with a custom controller or a controller extension during a postback request.

9818_02_06.png

The view state is decoded and used as the basis for updating the values on the page during a postback request.

Then expressions are evaluated and setters are executed.

The action is executed, on the successful completion data is update. If the postback request redirects the user to the same page, the view state is updated.

Send the results to the browser

Note: If we want to execute an action without performing validations on the input or data changes on the page, we can use immediate attribute with true value for a particular component.

The postback request can be ended up with a page redirect and sometimes the custom controller or the controller extension may be shared on both of the originating page and the redirected page. If the postback request contains an <apex:form> component, only the ID query parameter on a postback request is returned.

Note: The action attribute on the <apex:page> component is evaluated only during a get request. Once the user is redirected to another page, the view state and controller objects are deleted.

Validation Rules and Standard Controllers / Custom Controllers

Validation rules can be applied to custom or standard objects for validating data on insert and update operations. When we perform such operation on a Visualforce page, that uses a standard controller or a custom controller, and that record may cause a validation rule error, we can display the error on Visualforce page same as on standard pages. Validation rule has two options to select the error displaying position as top of the page and with the particular field. If we choose "top of the page", the error can be displayed by using <apex:pageMessages> or <apex:messages> component within the <apex:page>. If we choose "field" option, error will be shown in associated field resides next to the <apex:inputField> component. For example, you can try with the example page which given under the Building custom controller section. You can try the example by entering a non numeric character for "Unit Price" field. An error message will be displayed near to the Unit_Price__c field related <apex:inputField> component.

Using the transient Keyword

The "transient" key word is used for declaring variables and used in Apex classes. Declaring variable as transient causes to reduce the view state size. Variables with transient keyword cannot be saved and it should not be transmitted as a part of the view state of the particular Visualforce page. Transient variables are needed only for the duration of a page request.

The "transient" keyword is used in serializable Apex classes which mean classes that implement the Batchable or Schedulable interfaces. Following Apex objects are natively considered as transient;

PageReference

XmlStreamClasses

Collections

Most objects generated by system methods such as Schema.getGlobalDescribe

Static variables

JSONParser class instances

Following example has a transient datatime variable and non transient datatime variable. This example shows the main feature of transient variables. That is cannot be saved and should not be a part of the view state. When we click on the Refresh button, transient date will be recreated but the non-transient date will be continue with its original value.

<apex:page controller="TransientExampleController">

Non Transient Date: {!t1} <br/>

Transient Date : {!t2} <br/>

<apex:form >

<apex:commandLink value="Refresh"/>

</apex:form>

</apex:page>

public with sharing class TransientExampleController {

DateTime t1;

transient DateTime t2;

public String getT1() {

if (t1 == null) t1 = System.now();

return '' + t1;

}

public String getT2() {

if (t2 == null) t2 = System.now();

return '' + t2;

}

Considerations for Creating Custom Controllers and Controller Extensions

When we are creating custom controllers and controller extensions, keep following consideration in your mind.

Most important thing to keep in your mind is Apex governor limits.

Apex classes can be run in system mode and user mode by using respectively without sharing and with sharing. Sensitive data can be exposed in without sharing controllers.

The webservice methods must be defined as global. Other all the methods are public

Try to access the database in less time by using sets, maps, or lists. It will increase the efficiency of your code.

Apex methods and variables are not instantiated in a guaranteed order.

You cannot implement Data Manipulation Language (DML) in constructor method of a controller

You cannot define @future annotation for any getter method, setter method, or constructor method of a controller.

Primitive data types (String, Integer,etc) are passed by value and non-primitive Apex data types (list,maps,set,sObject,etc)are passed by reference to component’s controller



rev

Our Service Portfolio

jb

Want To Place An Order Quickly?

Then shoot us a message on Whatsapp, WeChat or Gmail. We are available 24/7 to assist you.

whatsapp

Do not panic, you are at the right place

jb

Visit Our essay writting help page to get all the details and guidence on availing our assiatance service.

Get 20% Discount, Now
£19 £14/ Per Page
14 days delivery time

Our writting assistance service is undoubtedly one of the most affordable writting assistance services and we have highly qualified professionls to help you with your work. So what are you waiting for, click below to order now.

Get An Instant Quote

ORDER TODAY!

Our experts are ready to assist you, call us to get a free quote or order now to get succeed in your academics writing.

Get a Free Quote Order Now