function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Michael MMichael M 

Maximum view state size limit (170KB) exceeded error

Hello, I am working on a VF page, on which users can upload files. After clicking save, I am getting shown a screen with this message: 

Maximum view state size limit (170KB) exceeded. Actual view state size for this page was 1,006.033KB

Any idea how I can stop this error message? The strange thing is that the file seems to be getting uploaded anyways, so I'm not sure what to do with that message.
Best Answer chosen by Michael M
VinayVinay (Salesforce Developers) 
Hi Michael,

You're basically trying to store every record in the database in the view state. Check about dynamic queries (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm) and this will greatly improve your code's performance and allow you to avoid view state size errors, heap limit exceptions, CPU timeouts, too many query rows, etc.

Check below reference for debugging size limit error.

https://help.salesforce.com/articleView?id=000321547&type=1&mode=1
https://help.salesforce.com/articleView?id=000323828&type=1&mode=1

Hope this helps...

Thanks,

All Answers

VinayVinay (Salesforce Developers) 
Hi Michael,

You're basically trying to store every record in the database in the view state. Check about dynamic queries (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm) and this will greatly improve your code's performance and allow you to avoid view state size errors, heap limit exceptions, CPU timeouts, too many query rows, etc.

Check below reference for debugging size limit error.

https://help.salesforce.com/articleView?id=000321547&type=1&mode=1
https://help.salesforce.com/articleView?id=000323828&type=1&mode=1

Hope this helps...

Thanks,
This was selected as the best answer
Maharajan CMaharajan C
Hi Michael,

Once the file is submitted in apex you can null the file or Attachment from class. This will keep the view state.
 
public Blob file {get;set;} 

public void submit() { 
	Attachment att = new Attachment(); 
	att.Name = fileName; 
	att.Body = file;
	att.ParentId = parent.Id; 
	att.Description = 'File Upload Done'; 
	insert att;    
	file = null;
    att  = null;
}

Thanks,
Maharajan.C
Michael MMichael M
Thank you both- both are helpful!