An Introduction to Visualforce View State   Leave a comment


Visualforce pages that contain a form component also contain an encrypted, hidden form field that encapsulates the view state of the page. This view state is automatically created, and as its name suggests, it holds the state of the page – state that includes the components, field values and controller state.

This article provides an introduction to view state, some code samples to show the effect on view state, as well as best practices for optimizing view state in order to improve page performance.

What is view state?

Let’s start by understanding the need for view state. In Figure 1, a user requests a web page with a simple form on it, and fills out the form and submits it. If the user’s input fails the validation rules for the form, the server responds with an error message – the user corrects the error and resubmits it successfully. Behind the scenes the browser is issuing HTTP requests.

Figure 1

The page is initially retrieved with a GET request and form submissions happen via POST requests. These POST requests are also called postbacks since the data on the form is being posted back to the same page. From the user perspective, this is a stateful interaction since the page state is changing based on its previous state. However HTTP is a stateless protocol, which means that the initial GET and the two subsequent POSTs are treated as independent requests for the page. As a result, some other mechanism is needed to persist state information across HTTP requests.

In Visualforce, page state is persisted as a hidden form field that is automatically inserted into a form when the page gets generated. We call this the view state of the page. The view state captures the state of the page — state of its associated controllers and extensions and the component tree on the page. The view state is posted back along with the other form data, which gives the server enough information to recreate the page state to which new changes can be applied. Please consult this section in Visualforce documentation to understand the order of execution for a Visualforce page.

What is contained in the view state?

The data in the view state should be sufficient to recreate the state of the page when the postback is received. To do this, it stores the following data

  • All non-transient data members in the associated controller (either standard or custom) and the controller extensions.
  • Objects that are reachable from a non-transient data member in a controller or controller extension.
  • The component tree for that page that represents the page’s component structure and the associated state which are the values applied to those components.
  • A small amount of data for Visualforce to do housekeeping.

View state data is encrypted and cannot be viewed with tools like Firebug. The view state inspector described below lets you look at the contents of view state.

Examining the view state

Developer environments have a View State Inspector, which lets you view the contents of the view state.

Figure 2

This information can help you in optimizing the view state size. Once enabled, it shows up as a tab in development mode. Figure 2 shows a screen shots of this new tool. The Visualforce Developer Guide contains details on how to use this tool.

View state in action

In the previous sections we looked at what is contained in the view state and how the view state inspector lets you view its contents. To make the concepts around view state a little more concrete, this section looks at a few sample pages and their associated view state.

Sample 1

Here we have a page that uses a standard controller with a single field. The associated view state is shown below.

01 <apex:page standardController="Account">
02 <apex:form >
03 <apex:pageBlock title="My Content" mode="edit">
04 <apex:pageBlockButtons >
05 <apex:commandButton action="{!save}" value="Save"/>
06 </apex:pageBlockButtons>
07 <apex:pageBlockSection title="My Content Section" columns="2">
08 <apex:inputField value="{!}"/>
09 </apex:pageBlockSection>
10 </apex:pageBlock>
11 </apex:form>
12 </apex:page>

Figure 3

Sample 2

The following listing shows a Visualforce page with a custom controller and a single field. Figure 4 shows the associated view state which contains an account instance since it has been declared as a non transient member variable in our controller. Notice how simple our controller code to update the account is.

01 <apex:page controller="MyController1" >
02 <apex:form >
03 <apex:pageBlock title="My Content" mode="edit">
04 <apex:pageBlockButtons >
05 <apex:commandButton action="{!save}" value="Save"/>
06 </apex:pageBlockButtons>
07 <apex:pageBlockSection title="My Content Section" columns="2">
08 <apex:inputField value="{!}"/>
09 </apex:pageBlockSection>
10 </apex:pageBlock>
11 </apex:form>
12 </apex:page>
14 public with sharing class myController1 {
15 public final Account account {get; set;}
17 public myController1() {
18 account = [select name from Account where id = :ApexPages.currentPage().getParameters().get('id')];
19 }
20 public PageReference save() {
21 update account;
22 return null;
23 }
24 }

Figure 4

Sample 3

Let’s modify the above example by making the account name and id, controller member variables. We will make the account name member transient, so only record Id is being saved in the view state. The page and the controller code is shown below. When this page is posted back, we will need to retrieve the record again, apply the new values and then update the database. This highlights the main benefit of view state – making the job of a developer easier by automatically maintaining state between postbacks.

01 <apex:page controller="myController" >
02 <apex:form >
03 <apex:pageBlock title="My Content" mode="edit">
04 <apex:pageBlockButtons >
05 <apex:commandButton action="{!save}" value="Save"/>
06 </apex:pageBlockButtons>
07 <apex:pageBlockSection title="My Content Section" columns="2">
08 <apex:outputLabel for="aName">Account Name:</apex:outputLabel>
09 <apex:inputText value="{!accountName}"/>
10 </apex:pageBlockSection>
11 </apex:pageBlock>
12 </apex:form>
13 </apex:page>
15 public with sharing class myController {
17 private final Id accountId ;
18 transient public final String accountName {get; set; }
20 public myController() {
21 Account account = [select Id, Name from Account where id = :ApexPages.currentPage().getParameters().get('id')];
22 accountId = account.Id ;
23 accountName = account.Name ;
24 }
26 public PageReference save() {
27 Account myAccount = [select name from Account where id = :accountId];
28 = accountName ;
29 update myAccount;
30 return null;
31 }
33 }

Figure 5

Sample 4

Finally, let’s add a new component to the page and observe the effect on view state. We will add a standard pageMessages component – the resulting view state now shows the controller state associated with this component.

01 <apex:page controller="myController1" >
02 <apex:form >
03 <apex:pageBlock title="My Content" mode="edit">
04 <apex:pageMessages/>
05 <apex:pageBlockButtons >
06 <apex:commandButton action="{!save}" value="Save"/>
07 </apex:pageBlockButtons>
08 <apex:pageBlockSection title="My Content Section" columns="2">
09 <apex:inputField value="{!}"/>
10 </apex:pageBlockSection>
11 </apex:pageBlock>
12 </apex:form>
13 </apex:page>

Figure 6

Best practices for optimizing view state

View state makes your job as a developer easier by automatically handling all the details for state management during postbacks. However, since the view state has to be transferred back and forth between the browser and, there could be a potential performance impact in terms of increased page load times when the view state becomes large. Visualforce also imposes a limit of 128K on your view state – if the view size exceeds this limit, an exception gets thrown. Let us look at a few best practices to optimize view state.

Minimize number of forms on a page

Assume a page contains two forms – form 1 and form 2. Irrespective of which form the user submits and causes a postback, the view state for the page needs to get transferred. To support this, each form on your page will have its own copy of view state. If the associated view state is large, instead of having multiple forms on a page, have a single form and use <apex:actionRegion> to submit portions of the form. This will ensure that only a single copy of the view state is associated with that page. In the example below, two forms are used to update Account fields and the related Contact attributes.

01 // Using two forms
02 <apex:page controller="MyController">
04 <apex:form>
05 <apex:commandButton action="{!saveAccount}" value="Update Account"/>
06 <!--Account attributes available for editing -->
08 </apex:form>
10 <apex:form>
11 <apex:commandButton action="{!saveContacts}" value="Update Contacts"/>
12 <!--Contact attributes available for editing -->
13 </apex:form>
15 </apex:page>

This can be combined into a single form by leveraging the <apex:actionRegion> component.

01 // Combining into single form and leveraging <apex:actionRegion>
02 <apex:page controller="MyController">
03 <apex:form>
04 <apex:commandButton action="{!saveAccount}" value="Update Account"/>
05 <!--Account attributes available for editing -->
07 <apex:actionRegion>
08 <apex:commandButton action="{!saveContacts}" value="Update Contacts"/>
09 <!--Contact attributes available for editing -->
10 </apex:actionRegion>
12 </apex:form>
13 </apex:page>

You can find additional details on <apex:actionRegion> component here.

Declare variables as transient to reduce view state

An instance variable declared as transient is not saved and is not transmitted as part of the view state. If a certain field is needed only for the duration of the page request and does not need to be part of the view state, declare it as transient. See an example below. Some Apex objects are automatically considered transient. For a full list of such objects and other details on transient please refer to the docs.

01 <apex:page controller="ExampleController">
02 The Current Time is : {!currentDateTime} <br/>
03 <apex:form>
04 <apex:commandLink value="refresh"/>
05 </apex:form>
06 </apex:page>
08 public class ExampleController {
10 transient DateTime currentDateTime;
12 public String getCurrentDateTime() {
13 if (currentDateTime == null) currentDateTime =;
14 return '' + currentDateTime;
15 }
16 }

Recreate state versus storing it in view state

View state should ideally contain only work in progress data e.g. current object being edited, multi-page wizard data etc. If you can reconstruct the data during postback, via a SOQL query or a web services call, do that instead of storing it in controller data members.

Use custom objects or custom settings to store large quantities of read only data

Let us say that your controller needs to call a web service and parse a large response object. Storing it in view state may not even be an option given the size. Marking it as transient would incur the cost of an additional web service call and parsing it again. In such instances, you could store the parsed response in a custom object and just store the record id to get to the parsed response. Custom settings provide another mechanism to cache data needed by your controller. Accessing custom settings is faster than access to custom objects since custom settings are part of your application’s cache and does not require a database query to retrieve the data. Please consult the online documentation for additional details on Custom Setting.

Refine your SOQL to only retrieve the data needed by the page

Only retrieve (and store) the fields you need and also filter the data to only retrieve data needed by the page.

Refactor your pages to make its view stateless

Instead of using apex:commandLink or apex:commandButton components (which needs to be inside a apex:form component) to invoke an action, use an apex:outputLink or other non action method instead and implement the action through an apex:page action attribute – where it makes sense. The following code shows two ways to invoke a controller method called proccessData() – first with a commandLink, and then with an outputLink and auxiliary page.

01 // On this page we use a commandLink to invoke a method. CommandLink should be inside a
02 // form and thus will have an associated view state
03 <apex:page controller="ExampleController" >
04 <b>Example with command link </b>
05 <br/><br/>
06 <apex:form >
07 <apex:commandLink value="Process Data" action="{!processData}"/>
08 </apex:form>
09 </apex:page>
12 //This page accomplishes the same without the need for a view state
13 <apex:page >
14 <b> Example -  using outputLink </b>
15 <br/> <br/>
16 <apex:outputLink value="{!$Page.MyPage2}">Process Data</apex:outputLink>
17 </apex:page>
19 // On MyPage2 you can also invoke a method with an action attribute
20 <apex:page controller="ExampleController" action="{!processData}">
21 </apex:page>

Consider doing your own state management in certain cases

In certain cases you may want to bypass the view state mechanism offered by Visualforce and do your own state management. In such cases, use a HTML FORM instead of apex:form. This technique is useful for dealing with Visualforce pages that may have to be served to mobile devices where the view state may be too large for the embedded browsers.


View state makes your job as a developer easier by automatically managing state during postbacks. The view state is very much under your control – and you can optimize the size of the view state by paying attention to transient variables, the number of forms on a page, using custom settings to store data and so on.


About the Author

Nick Simha is a Partner Enablement Manager and Platform Evangelist working with’s consulting partners to help them build innovative cloud applications for our customers.


Posted 2011年01月23日 by gw8310 in 未分类


Fill in your details below or click an icon to log in: 徽标

You are commenting using your account. Log Out /  更改 )

Google+ photo

You are commenting using your Google+ account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )


Connecting to %s

%d 博主赞过: