+ Start a Discussion
VRKVRK 

view state Error when upload attachements for CaseDocument Object

Hi
When upload attachements for Case Documnet Object getting View State Error .
Below scenario , getting View State Error:
Business tryng to upload PDF Documents more than 2 mb, getting this View State Error. 

When try to upload small size files more than 30+ also not getting this Error .
But, in our code we didn't mention anywhere File Size , pls let me know if required any modifications on below code :
VF Page :
---------

<apex:page docType="html-5.0" standardController="Case" extensions="CaseDocumentFileUploadCX" title="Upload Case document">
    <apex:includeScript value="{!URLFOR($Resource.jquery)}"  />
    <apex:form id="uploadForm">

    <script>
        var $jQuery = jQuery.noConflict();

        $jQuery(document).ready(function(){
            var $uploadNameInput = $jQuery('[id$="uploadFileName"]');
            //$uploadNameInput.prop('readonly', true);

            $jQuery('[id$="fileUploadInput"]').on('change', function(){
                var $this = $jQuery(this);
                $jQuery('[id$="documentLabel"]').val($this.val().split(/(\\|\/)/g).pop());
                //$uploadNameInput.prop('readonly', false);
                $uploadNameInput.val($this.val().split(/(\\|\/)/g).pop());
                //$uploadNameInput.prop('readonly', true);
                //refreshPage();
            });
            
            
        });
        
        </script>
        <script type="text/javascript">
        var caseDocId;
        var caseId = '{!caseId}';
        function evaluateCaseDoc() {
            $jQuery('#okuploadbtn').hide();
            $jQuery('#msg').text('Uploading');


            Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.CaseDocumentFileUploadCX.evaluate}',
                '{!jsonString}',
                '{!uploadFileName}',
                function(result1, event){
                    caseDocId = result1;
                    Visualforce.remoting.Manager.invokeAction(
                        '{!$RemoteAction.CaseDocumentFileUploadCX.executeRequest}',
                        result1,
                        function(result2, event){
                            $jQuery('#msg').text(result2);
                            if(result2 === 'Document Upload SUCCESSFUL!'){
                                $jQuery('#donebtn').show();
                            }else{
                                $jQuery('#retrybtn').show();
                            }
                        }, 
                        {escape: true}
                    );
            }, 
                {escape: true}
            );
        }
        
        </script>
        <!--<apex:actionFunction name="createCaseDoc" action="{!evaluate}" />-->
        <apex:actionFunction name="reupload" action="{!reupload}" />
        <apex:actionFunction name="loadCaseDoc" action="{!loadCaseDoc}" />
        <apex:outputPanel id="showstate"/>
        <apex:pageBlock id="filePageBlock" >
            <apex:pageMessages />
            <apex:pageBlockSection columns="1" title="File selection" id="fileSelection" >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="{!$ObjectType.CaseDocument__c.Fields.FilePath__c.Label}" />
                    <apex:inputFile value="{!fileUpload.body}" filename="{!fileUpload.name}" id="fileUploadInput" fileSize="{!caseDoc.FileSize__c}" contentType="{!caseDoc.MimeType__c}" style="width:100%;height:20px;" />
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock id="fileSelectionDetails" >
            <apex:pageBlockSection columns="1" title="File upload details">
                <apex:inputField value="{!caseDoc.Name}" label="{!$ObjectType.CaseDocument__c.Fields.Name.Label}" id="documentLabel" required="true" style="width:50%;" />
                <apex:inputText value="{!uploadFileName}" label="File name" id="uploadFileName" style="width:50%;" />
                <apex:inputField value="{!caseDoc.MimeType__c}"  rendered="false" label="{!$ObjectType.CaseDocument__c.Fields.MimeType__c.Label}" style="width:50%;"  />
                <apex:inputField value="{!caseDoc.BusinessCode__c}" style="width:50%;" />
                <apex:inputField value="{!caseDoc.CaseId__c}" label="{!$ObjectType.CaseDocument__c.Fields.CaseId__c.Label}" id="fileUploadCase" style="width:50%;"  />
            </apex:pageBlockSection>
            
            <apex:commandButton action="{!showCheckOpen}" value="Upload" />
        </apex:pageBlock>
        
        <apex:outputPanel id="showFileOpenPopUp">
          <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!showFileOpenPopUp}"/>
            <apex:outputPanel styleClass="custPopup overlayDialog cssDialog inlineEditDialog" style="display:block; visibility:visible;" layout="block" rendered="{!showFileOpenPopUp}">
              <div class="topRight">
                <div class="topLeft">
                  <h2></h2>
                </div>
              </div>
              <br />
              <apex:outputPanel id="msgLabelClass" rendered="{!showFileOpenPopUp}">
                  <div id="msg">{!$Label.CheckFileOpenDialogMessage}</div>
                  <br />
                  <br />
              </apex:outputPanel>                         
              <div class="buttons zen" style="margin-left: 100px; ">
                 <input id = "okuploadbtn" class="btn" width="20px" type="button" value="{!$Label.CheckFileOpenDialogOkButton}" onclick="evaluateCaseDoc();return false; "  />
                 <input id = "donebtn" style="display:none;" class="btn" width="20px" type="button" value="{!$Label.CheckFileOpenDialogOkButton}" onclick="window.open('/'+caseDocId,'_self');"  />
                <input id = "retrybtn" style="display:none;" class="btn" width="20px" type="button" value="{!$Label.CheckFileOpenDialogOkButton}" onclick="window.open('/apex/CaseDocumentFileUpload?id='+caseId,'_self');"  />
                </div>
            </apex:outputPanel>
        </apex:outputPanel>
                
    </apex:form>

    <style>

      [id$='msgLabelClass'] {
         display: inline;        
      }

      [id$='msgLabelClass'] > label {
         margin-left: 10px;
        block-width: 260px;
         display: inline-block;
      }

      [id$='msgLabelClass'] + table {
         margin-left: 10px;
         display: inline;
         vertical-align: middle;
         width: auto;
      }

      .custPopup{
         background-color: white;
         z-index: 100;
         left: 50%;
         position: absolute;
         /* These are the 3 css properties you will need to change so the popup 
            displays in the center of the screen. First set the width. Then set 
            margin-left to negative half of what the width is. You can add 
            the height property for a fixed size pop up if you want.*/
         width: 300px;
         height: 130px;
         margin-left: -250px;
         top:100px;
         padding-bottom: 15px;
      }

      .custPopup h2 {
                margin-right: 30px;
      }
      
      .popupBackground{
                background-color:black;
                opacity: 0.20;
                filter: alpha(opacity = 20);
                position: absolute;
                width: 100%;
                height: 100%;
                top: 0;
                left: 0;
                z-index: 99;
      }
    </style>    
</apex:page>

Apex class:
----------------
/**
 * @description Extension controller class for Case Document file upload functionality

 */
global with sharing class CaseDocumentFileUploadCX {
    public Document fileUpload {get;set;}
    public String uploadFileName {get;set;}
    public CaseDocument__c caseDoc {get;set;}
    public Case currentCase {get;set;}
    public Integer fileSize {get;set;}
    public String jsonString {get;set;}
    //19.JAN.2015 Yogesh Gupta, NYLIM  Added new Dialog
    public Boolean showFileOpenPopUp{get;set;}
    public String caseDocId {get;set;}
    public String caseId {get;set;}
    private boolean isSuccess;

    private static String injectHeader = ' DMS Document Maintenance (From Case Document)'; 
    private static String injectTempHeader = ' DMS Document Maintenance Temp (From Case Document)';
    private static Set<String> injectStates = new Set<String>{'5.4.a'};
    private static Set<String> injectTempStates = new Set<String>{'4.2.a','4.1.a','5.4.b'};
    

    global CaseDocumentFileUploadCX(ApexPages.StandardController controller) {
        currentCase = (Case) controller.getRecord();
        caseId  = currentCase.Id;
        fileUpload = new Document();
        uploadFileName = '';
        fileSize = 0;
        caseDoc = new CaseDocument__c();
        caseDoc.CaseId__c = currentCase.Id;
        caseDoc.MimeType__c = '';
        isSuccess = false;
    }

     @RemoteAction
    global static String evaluate(String jsonString, String uploadFileName ){
        PageReference newPage = null;
            
        System.debug('uploadFileName ::: ' + uploadFileName);
        String caseDocId;
         CaseDocument__c caseDoc = (CaseDocument__c) JSON.deserialize(jsonString, CaseDocument__c.class);
        //hideFileOpenPopUpPanel();
        if (uploadFileName != null && uploadFileName != '') {
            // Fetch file upload settings for the current user's profile
            FileUploadSettings__c fileUploadSettings = FileUploadSettings__c.getInstance(UserInfo.getProfileId());
            if (fileUploadSettings == null) {
                fileUploadSettings = FileUploadSettings__c.getOrgDefaults();
            }
            
            // Build the file path
            Id uid = UserInfo.getUserId();
            List<String> userFields = new List<String>{
                'Id',
                'FederationIdentifier'
            };
            String queryString = CS_UtilSObject.buildQuery(Schema.SObjectType.User, userFields);
            queryString += 'WHERE Id = :uid';
            User u = Database.query(queryString);
            //User u = [SELECT Id, FederationIdentifier FROM User WHERE Id = :uid];
            if (u != null) {
                caseDoc.FilePath__c = fileUploadSettings.get('NetworkFolderRootPath__c') + '\\' + u.FederationIdentifier + '\\' + uploadFileName;
            } else {
                ApexPages.Message errMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'User not found');
                ApexPages.addMessage(errMsg);
            }
            
            try {
                CaseDocumentTrigger_Handler.runAfterInsert = false;
                CaseDocumentTrigger_Handler.runAfterUpdate = false;
                
                insert caseDoc;
                caseDocId = caseDoc.Id;
                System.debug('* ** *** insert ' + caseDocId);
                
                
                newPage = New PageReference('/apex/CaseDocumentFileUpload2?id=' + caseDoc.id);
                newPage.setRedirect(true);
            } catch (Exception e) {
                //ApexPages.Message errMsg = new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage());
                //ApexPages.addMessage(errMsg);
                System.debug('Error ::: ' + e);
            }
        } else {
            ApexPages.Message errMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Please upload a document');
            ApexPages.addMessage(errMsg);
        }

        return caseDocId;
    }
    
    
    public PageReference showCheckOpen(){
        showFileOpenPopUp = true;
        jsonString = JSON.serialize(caseDoc);
        fileUpload = new Document();
        caseDoc = new CaseDocument__c();
        return null;
    }
    
    @RemoteAction
    global static String executeRequest(String caseDocId) {
            System.debug('* ** *** executeRequest');
            System.debug('* ** *** caseDocId ' + caseDocId);
            List<CaseDocument__c> caseDocList = [SELECT Id, IntegrationState__c, FilePath__c  FROM CaseDocument__c WHERE Id = :caseDocId LIMIT 1];
            if(caseDocList.isEmpty()){
                return 'UPLOAD FAILURE: An unexpected error has occured. Please try to upload document again. If you continue to experience difficulties, please contact your system administrator.';
            }
            
            CaseDocumentTrigger_Handler.runAfterInsert = false;
            CaseDocumentTrigger_Handler.runAfterUpdate = false;
            CaseDocumentTrigger_Handler.runBeforeUpdate = false;
                
            CaseDocument__c  caseDoc = caseDocList.get(0);
            if(injectStates.contains(caseDoc.IntegrationState__c)){
                if(!Test.isRunningTest()) CaseDocumentTrigger_Handler.executeRequests(new Set<String>{caseDoc.id},injectHeader,true); 
            }else{
                if(!Test.isRunningTest()) CaseDocumentTrigger_Handler.executeRequests(new Set<String>{caseDoc.id},injectTempHeader,true); 
            }
            
            PageReference newPage;
            caseDoc = [SELECT Id, CaseId__c, DMSInject_Code__c, DMSInject_Status__c FROM CaseDocument__c WHERE Id = :caseDocId];
            
            if(caseDoc.DMSInject_Status__c  == 'SUCCESS'){
                boolean isSuccess  = true;
                
                return 'Document Upload SUCCESSFUL!';
            }else{
                delete caseDoc;
                if(caseDoc.DMSInject_Code__c == '01'){
                    return 'DOCUMENT NOT FOUND: Please ensure that the document that you are trying to upload is located in the proper location and try again.';
                }else{
                    return 'UPLOAD FAILURE: An unexpected error has occured. Please try to upload document again. If you continue to experience difficulties, please contact your system administrator.';
                }
                
               
            }
            return 'UPLOAD FAILURE: An unexpected error has occured. Please try to upload document again. If you continue to experience difficulties, please contact your system administrator.';
            //return  New PageReference('/apex/CaseDocumentFileUpload2?id=' + caseDoc.id);

    }
   
   public PageReference reupload(){
        PageReference  newPage  =  New PageReference('/apex/CaseDocumentFileUpload?id=' + caseId);
        newPage.setRedirect(true);
        return newPage;  
    }
    
    public PageReference loadCaseDoc(){
        PageReference  newPage  = New PageReference('/' + caseDocId);
        
        newPage.setRedirect(true);
        return newPage;  
    }
    
    public PageReference showFileOpenPopUpPanel(){
        showFileOpenPopUp=True;
        return null;
    }

    public PageReference hideFileOpenPopUpPanel(){
        showFileOpenPopUp = False;
        return null;
    }   
}

Pls let me know any one have idea, how to fix View State error when upload large files for CaseDocumnet Object
Thanks
VRK

ShirishaShirisha (Salesforce Developers) 
Hi,

Greetings!

It is difficult to provide you the causes of the errors by seeing the code as it could be because of the components you used or the SOQL queries which are returning huge records.

So,I would suggest you to go through the below document (https://help.salesforce.com/articleView?id=000323828&type=1&mode=1) for the causes and how to troubleshoot the issue.

You need to enable developer Mode to check which components are using the high view.

Reference:https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_tools_edit_toolbar.htm

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri