Monday, 21 September 2015

Maximum View State Size Limit (135kB) Exceeded

I bet many Salesforce Developer face this issue while working on  Visualforce Pages where they are trying to do something like - "Render VF page as PDF", "Upload File", etc.

Problem :  Maximum View State Size limit (135kB) exceeded

Error : Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 838.719KB   (<- this last digits can be any)


- View state size of your Visualforce pages must be under 135KB. 

- The View State tab shows you which elements on your page are taking up that space. A smaller view state size generally means quicker load times.
- In order to avoid this error, minimize your pages' view state. You can optimize your Apex controller code and remove any superfluous Visualforce components used.

Try following :
  • If you notice that a large percentage of your view state comes from objects used in controllers or controller extensions,consider refining your SOQL calls to return only data that's relevant to the Visualforce page. 

  • If your view state is affected by a large component tree, try reducing the number of components your page depends on.

  • Only those variables which are used on visual force page should be PUBLIC rest all variables should be PRIVATE, if they are not used by any other class.

  • Make variables TRANSIENT which leads to increase the view state size, which shouldn't be transmitted as part of the view state for visual force page. Transient variables are not stored in the view state. 
  • I mean simply put "transient" keyword in front of your variable declarations.
  • We should nullify all the instance of objects which are no longer in use, Like clear your object instance, Lists, Maps,etc.   (Example : after done with working on List in for loop simply do -> mylist=null;  after for loop)

Try this if you are comfortable with JavaScript : 

The best way to achieve this use case is to use AJAX API.  After you have fixed view state error, it will hit apex heap limit of 6MB. But using AJAX API you can upload files of size up to 25MB, which is the maximum size limit of attachments in salesforce.

You just need to pass the parent Id and the image file. For sample code please check THIS POST.

Useful Links: 

View State

Using Transient keyword

Best Practices for Improving Visualforce Performance