0

Following is the code in which I am getting a view state error :

VF PAGE:

<apex:page standardController="Technical_Verification__c" extensions="tvDocUpload" sidebar="false" showHeader="false"  readonly="true">

    <head>
        <apex:includeScript value="{!URLFOR($Resource.ExifJar, '/jquery-1.7.1.js')}" />
        <apex:includeScript value="{!URLFOR($Resource.ExifJar, '/exif.js')}" />

        <script>
        window.resizeTo( 870, 300)
            function redirectTo() {
                var vlu = '{!$CurrentPage.Parameters.flg}';
                if (vlu == 'true' || vlu == true) {
                    opener.location.href = '/{!$CurrentPage.parameters.id}';
                    close();
                }
            }
            redirectTo();
        </script>
        <script>
            function getGPSdata(e) {
                EXIF.getData(e.files[0], function() {
                    var lat = EXIF.getTag(this, "GPSLatitude");
                    lat = lat + "";   
                    var arrLat = lat.split(",");
                    var deciLat = parseFloat(arrLat[0]) + parseFloat(arrLat[1]/60) + parseFloat(arrLat[2]/3600);

                    var longi = EXIF.getTag(this, "GPSLongitude");
                    longi = longi + "";
                    var arrLong = longi.split(",");
                    var deciLong = parseFloat(arrLong[0]) + parseFloat(arrLong[1]/60) + parseFloat(arrLong[2]/3600);

                    if(lat != 'undefined' && longi != 'undefined'){
                    //alert('1');
                        document.querySelectorAll('[id$="GPSLatitude1"]')[0].value = deciLat;
                        document.querySelectorAll('[id$="GPSLongitude1"]')[0].value = deciLong;
                        document.querySelectorAll('[id$="GPSLatitude2"]')[0].innerHTML = deciLat;
                        document.querySelectorAll('[id$="GPSLongitude2"]')[0].innerHTML = deciLong;
                    }else{
                    //alert('2');   
                        alert('GeoLocation is missing!');  
                        document.querySelectorAll('[id$="GPSLatitude1"]')[0].value = null;
                        document.querySelectorAll('[id$="GPSLongitude1"]')[0].value = null;
                        document.querySelectorAll('[id$="GPSLatitude2"]')[0].innerHTML = null;
                        document.querySelectorAll('[id$="GPSLongitude2"]')[0].innerHTML = null;
                    }


                    var str = EXIF.getTag(this, "DateTimeOriginal") || 'undefined1';
                    //alert(str)
                    if(str == 'undefined1'){
                    //alert('3');
                        alert('Created Date is missing!');  
                        document.querySelectorAll('[id$="DateCareated1"]')[0].value = null;
                        document.querySelectorAll('[id$="DateCareated2"]')[0].innerHTML = null;
                        document.querySelectorAll('[id$="CreatedTime1"]')[0].value = null;
                        document.querySelectorAll('[id$="CreatedTime2"]')[0].innerHTML = null;

                    }else{
                    //alert('4');
                        var str1 = str.split(" ");
                        var str2 = str1[0].split(":");
                        var str3 = str1[1].split(":");

                        document.querySelectorAll('[id$="DateCareated1"]')[0].value = str2[1] + '/' + str2[2] + '/' + str2[0] ;
                        document.querySelectorAll('[id$="DateCareated2"]')[0].innerHTML = str2[1] + '/' + str2[2] + '/' + str2[0];

                        document.querySelectorAll('[id$="CreatedTime1"]')[0].value = str1[1] ;
                        document.querySelectorAll('[id$="CreatedTime2"]')[0].innerHTML = str1[1] ;

                    }

                });
            }

             function showLoader(){
                    //alert('inside');
                    var status = document.getElementById("loaderStatus");
                    //alert(status);
                    status.style.display = 'block';
                }
        </script>
    </head>
    <apex:form id="frm">

        <apex:pageBlock title="Upload Image" tabStyle="Technical_Verification__c" id="pb">
            <apex:pageMessages />
            <apex:pageBlockSection collapsible="false" columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Image Type" />
                    <apex:selectList size="1" value="{!attContentType}">
                        <apex:selectOptions value="{!contentTypeList}"></apex:selectOptions>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Image" />
                    <apex:inputFile value="{!att.Body}" fileName="{!att.Name}" onchange="getGPSdata(this)" contentType="{!att.ContentType}" />
                </apex:pageBlockSectionItem>
                <!---  
                <apex:pageBlockSectionItem >
                        <apex:outputLabel value="Description"/>                      
                        <apex:inputText value="{!att.Description}"/> 
               </apex:pageBlockSectionItem>
               --->
               <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Image Type" style="display:none;" />
                    <apex:inputText style="display:none;" value="{!doc.Location__Latitude__s}" id="GPSLatitude1" />
                </apex:pageBlockSectionItem>

                <apex:outputText value="{!doc.Location__Latitude__s}" id="GPSLatitude2" />

                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Image Type" style="display:none;" />
                    <apex:inputText style="display:none;" value="{!doc.Location__Longitude__s}" id="GPSLongitude1" />
                </apex:pageBlockSectionItem>

                <apex:outputText value="{!doc.Location__Longitude__s}" id="GPSLongitude2" />

                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Image Type" style="display:none;" />
                    <apex:inputText style="display:none;" value="{!doc.Created_Date__c}" id="DateCareated1" />
                </apex:pageBlockSectionItem>

                <apex:outputText value="{!doc.Created_Date__c}" id="DateCareated2" />

                 <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Image Type" style="display:none;" />
                    <apex:inputText style="display:none;" value="{!doc.Created_Time__c}" id="CreatedTime1" />
                </apex:pageBlockSectionItem>
                <apex:outputText value="{!doc.Created_Time__c}" id="CreatedTime2" />

            </apex:pageBlockSection>

            <center>
                <apex:actionStatus id="status">
                    <apex:facet name="start">
                        <div style="width: 500px;">
                            <img src="/img/loading24.gif" style="vertical-align:middle;" />
                            <span style="margin-left: 10px; font-size: 12px; font-weight: bold; color: #000000;">Please wait while we are uploading the image...</span>
                        </div>
                    </apex:facet>
                </apex:actionStatus>
            </center>


                <div style="width: 500px;display:none;" id="loaderStatus">
<!--                   <img src="/img/loading24.gif" style="vertical-align:middle;" /> -->
<!--                   <span style="margin-left: 10px; font-size: 12px; font-weight: bold; color: #000000;">Please wait while we are uploading the image...</span> -->
                        <div class="waitingSearchDiv" id="el_loading" style="background-color: white;
                               height: 100%;opacity:0.65;width:100%;"> 
                            <div class="waitingHolder" style="top: 74.2px; width: 91px;">
                                <img class="waitingImage" src="/img/loading32.gif"  title="Please Wait..." />
                                <span class="waitingDescription"><p style="font-size: 24px;">Saving...</p></span>
                            </div>
                        </div>
                </div>


        <apex:pageBlockButtons location="bottom">
            <apex:commandButton value="Save" action="{!saveDocument}" onclick="showLoader();"/> &nbsp;
            <apex:commandButton value="Cancel" action="{!cancelDocument}" status="sts" />
        </apex:pageBlockButtons>
        </apex:pageBlock>
        <apex:actionStatus id="sts" startText="Uploading ..." startStyle="color:red;font-weight:bold;" />
    </apex:form>
</apex:page>

Controller :

public class tvDocUpload{

    public Attachment att {get;set;}
    public Document__c doc {get;set;}
    private Transient Blob resume {get; set;}
    public Boolean isErr {get;set;}
    public List<SelectOption> contentTypeList {get;set;}
    public String attContentType {get;set;}
    String techViewId;

    public tvDocUpload(){
        init(); 
    }

    public tvDocUpload(ApexPages.StandardController controller) {
        init();
    }

    private void init(){
        att        = new Attachment();
        doc        = new Document__c();
        //doc.Location__Longitude__s = 0;
        //doc.Location__Latitude__s = 0;
        techViewId = ApexPages.CurrentPage().getParameters().get('id');

        doc.Technical_Verification__c = techViewId;
        String flag = ApexPages.CurrentPage().getParameters().get('flg');
        fillUpContents();
        if(flag == 'true'){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Uploaded successfully...'));
        }
    }

    // fillup to contentTypeList records
    private void fillUpContents(){
        contentTypeList  = new List<SelectOption>();
        contentTypeList.add(new SelectOption('Other','Other'));
        contentTypeList.add(new SelectOption('Road with property Visible','Road with property Visible'));
        contentTypeList.add(new SelectOption('Property Front','Property Front'));
        contentTypeList.add(new SelectOption('Material on site','Material on site'));  
        contentTypeList.add(new SelectOption('Interior 1','Interior 1'));
        contentTypeList.add(new SelectOption('Interior 2','Interior 2'));

        contentTypeList.sort();
        attContentType = contentTypeList[0].getValue();
    }

    public pageReference saveDocument(){
         pageReference pg = saveProcess(false);
         return pg;
    }

    public pageReference saveDocumentSF1(){
         pageReference pg = saveProcess(true);
         return pg;
    }

    private pageReference saveProcess(Boolean isSF1){
        isErr = false;

            String code = '';
            String oppName = '';
            String oppLoanNumber = '';
            List<Technical_Verification__c> techObjList = new List<Technical_Verification__c>();
            if(string.isNotBlank(techViewId))
              techObjList  = [select id,Application__c,Application__r.Name, Application__r.Loan_Number__c from Technical_Verification__c where id =: techViewId];

            if(techObjList.size()>0){
                oppName = techObjList[0].Application__r.Name;
                oppLoanNumber = techObjList[0].Application__r.Loan_Number__c;
            }
            oppName = string.isNotBlank(oppName) ? oppName  : '';   
            oppLoanNumber = string.isNotBlank(oppLoanNumber ) ? oppLoanNumber : '';
            System.debug('att--> '+att);
            System.debug('att.Name--> '+att.Name);
            System.debug('att.Body--> '+att.Body);
            code = oppLoanNumber +' = '+oppName;    
            if(String.isNotBlank(attContentType)){
                code = code.trim().startsWith('=') ? code.trim().remove('=') : code;
                string fileName = att.Name;
                string ext = '';
                if(att.Name.contains('.'))
                    ext = att.Name.substring(att.Name.lastIndexOf('.')) ;
                att.Name = code+' = '+attContentType+ext;

                att.Name = att.Name.trim().startsWith('=') ? att.Name.trim().remove('=') : att.Name; 
            }
            try{
            doc.Document_Name__c  =     att.Name;

            insert doc;
            att.ParentId = doc.Id;
            insert att; 
            doc.Doc_Id__c = att.id;
            update doc;

            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Uploaded successfully...'));
            if(isSF1){
                return new PageReference('/'+techViewId);
            }else{
                return new PageReference('/apex/TechnicalVerificationDocUpload?flg=true&id='+techViewId);
            }
        }Catch(Exception e){
            isErr = true;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error,e.getMessage()));
        }
        finally{
                att.Body = null; // -- clears the viewstate
                att = new Attachment();
        }
        return null;
    }

    public pageReference cancelDocument(){
        return new PageReference('/apex/TechnicalVerificationDocUpload?flg=true&id='+techViewId);
    }

    public PageReference cancelDocumentSF1(){
        return new PageReference('/'+techViewId);
    }
}
  • try adding static or transient keyword to attachment att, public static Attachment att {get;set;} or public transient Attachment att {get;set;} – Anurag A Jun 29 '16 at 13:01
0

try this: att = null instead of att.Body = null

I also recommend to use lazy load pattern for file:

public Attachment doc {
    get {
        if (doc == null) {
            doc = new Attachment();
        }
        return doc;
     }
     set;
}

Maximum view state size limit (135KB) exceeded You have to clear file from view state after saving. View state is mechanism that is used to interaction between page and controller. For every request it is sent to controller and back to page. File is also included in it and after saving it in controller, it goes back to page in view state, so you have either to clear it or mark as transient

Read this article for more detailed info: https://developer.salesforce.com/page/An_Introduction_to_Visualforce_View_State

  • I replaced it with att = null, but I am still getting the same error! – user24524 Jun 29 '16 at 11:27
  • @user24524 try 'transient' keyword – Vladyslav K Jun 29 '16 at 12:19
0

Perhaps the view state is built at the time the PageReference is created i.e. before the finally executes? A way to eliminate that possibility is to clear the body immediately after the insert:

insert att; 
att.Body = null;
  • I did that but still getting the error: – user24524 Jun 29 '16 at 11:38
  • @user24524 Yeah I can't see what is wrong so that was pretty much trying to invent a cause... – Keith C Jun 29 '16 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.