0

This question already has an answer here:

I have the following code and i am just getting the following error, How can i reduce the size of view state ?

enter image description here

Maximum view state size limit (135KB) exceeded" error message

    public class MyPagingController
{
    private List<Quote> quotes;
    private List<Quote> pageQuotes;
    private String sortDirection = 'DESC';
    private String sortExp = 'createdDate';
    private Integer pageNumber;
    private Integer pageSize;
    private Integer totalPageNumber;
    public String searchQuoteName { get; set; }
    public String searchQuoteNumber { get; set; }

    public Integer getPageNumber()
    {
        return pageNumber;
    }

    public String sortExpression
    {
        get 
        {
            return sortExp;
        } 
        set
        {
            if (value == sortExp)
                sortDirection = (sortDirection == 'ASC')? 'DESC' : 'ASC';
            else
                sortDirection = 'ASC';
            sortExp = value;
        }
    }
    public String getSortDirection()
    {
        if (sortExpression == null || sortExpression == '')
            return 'ASC';
        else
            return sortDirection;
    }

    public void setSortDirection(String value)
    {  
        sortDirection = value;
    }

    public List<Quote> getQuotes()
    {
        return pageQuotes;
    }
    public Integer getPageSize()
    {
        return pageSize;
    }
    public Boolean getPreviousButtonEnabled()
    {
        return !(pageNumber > 1);
    }
    public Boolean getNextButtonDisabled()
    {
        if (quotes == null) return true;
        else
        return ((pageNumber * pageSize) >= quotes.size());
    }

    public Integer getTotalPageNumber()
    {
        if (totalPageNumber == 0 && quotes !=null)
        {
            totalPageNumber = quotes.size() / pageSize;
            Integer mod = quotes.size() - (totalPageNumber * pageSize);
            if (mod > 0)
                totalPageNumber++;
            }
        return totalPageNumber;
    }
    public MyPagingController()
    {
        pageNumber = 0;
        totalPageNumber = 0;
        pageSize = 20;
        ViewData();
    }

    public PageReference ViewData()
    {
        quotes = null;
        totalPageNumber = 0;        
        BindData(1);        
        return null;
    }

    private void BindData(Integer newPageIndex)
    {
        try
        {
            string sortFullExp = sortExpression  + ' ' + sortDirection;

            string searchQuoteName = searchQuoteName;
            system.debug('searchQuoteName ==== '+searchQuoteName);

            String searchQuery = '';
            String s = '';
            String squote = '';

            if(searchQuoteName != null){
                s = '\'%' + searchQuoteName + '%\''; 
                searchQuery = ' WHERE Name LIKE '+s; 
            }

            if(searchQuery != ''){
                if(searchQuoteNumber != null){
                    squote = '\'%' + searchQuoteNumber + '%\''; 
                    searchQuery += ' AND QuoteNumber LIKE '+squote; 
                }    
            }else{
                if(searchQuoteNumber != null){
                    squote = '\'%' + searchQuoteNumber + '%\''; 
                    searchQuery = ' WHERE QuoteNumber LIKE '+squote; 
                }
            }

            system.debug('searchquery ===='+searchQuery);

            if (quotes == null)                
                system.debug('Select Id, Name, Opportunity.Name, QuoteNumber, TotalPrice, CreatedDate, GrandTotal from Quote '+searchQuery +' order by ' +sortFullExp);
                quotes = Database.query('Select Id, Name, Opportunity.Name, QuoteNumber, TotalPrice, CreatedDate, GrandTotal, CreatedById, LastModifiedById from Quote '+searchQuery +' order by ' +sortFullExp+ ' Limit 10000');
                pageQuotes = new List<Quote>{};
                Transient Integer counter = 0;
                Transient Integer min = 0;
                Transient Integer max = 0;
                if (newPageIndex > pageNumber)
                {
                    min = pageNumber * pageSize;
                    max = newPageIndex * pageSize;
                }
                else
                {
                    max = newPageIndex * pageSize;
                    min = max - pageSize;
                }

                for(Quote a : quotes)
                {
                    counter++;
                    if (counter > min && counter <= max)
                        pageQuotes.add(a);
                }
                pageNumber = newPageIndex;
                if (pageQuotes == null || pageQuotes.size() <= 0)
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Data not available for this view.'));
                }
        catch(Exception ex)
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,ex.getMessage()));
        }
    }

    public PageReference nextBtnClick() {
        BindData(pageNumber + 1);
        return null;
    }

    public PageReference previousBtnClick() {
        BindData(pageNumber - 1);
        return null;
    }
    public PageReference Search() {
        //BindData(pageNumber);
        BindData(1);
        return null;
    }
}

VF Page :

<apex:pageBlockTable value="{!quotes}" var="c" rendered="{!NOT(ISNULL(quotes))}" rows="{!PageSize}">

     <apex:column width="15%">
       <apex:facet name="header">   
         <apex:commandLink action="{!ViewData}" value="Quote Name{!IF(sortExpression=='name',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort">
           <apex:param value="name" name="column" assignTo="{!sortExpression}" ></apex:param>
         </apex:commandLink>
       </apex:facet>
       <apex:outputlink value="/apex/QuoteDetail?id={!c.Id}">{!c.name}</apex:outputlink>
     </apex:column>

      <apex:column width="35%" headerValue="Opportunity Name">
        <apex:outputlink value="/{!c.OpportunityId}" target="_blank">{!c.Opportunity.Name}</apex:outputlink>
     </apex:column>

     <apex:column width="10%" value="{!c.QuoteNumber}">
       <apex:facet name="header">   
         <apex:commandLink action="{!ViewData}" value="Quote Number{!IF(sortExpression=='QuoteNumber',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdNumberSort">
           <apex:param value="QuoteNumber" name="column" assignTo="{!sortExpression}" ></apex:param>
         </apex:commandLink>
       </apex:facet>
     </apex:column>

      <apex:column width="10%" headerValue="Quote Amount" value="{!c.GrandTotal}"/>

      <apex:column width="15%" value="{!c.createdDate}">
       <apex:facet name="header">   
         <apex:commandLink action="{!ViewData}" value="Date{!IF(sortExpression=='createdDate',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdCreatedAtSort">
           <apex:param value="createdDate" name="column" assignTo="{!sortExpression}" ></apex:param>
         </apex:commandLink>
       </apex:facet>
     </apex:column>

      <apex:column width="35%" headerValue="Created By">
          <apex:outputField value="{!c.createdById}"/>
          <!--<apex:outputField value="{!c.createdDate}"/>-->
      </apex:column>

      <apex:column width="35%" headerValue="Modified By">
          <apex:outputField value="{!c.LastModifiedById}"/>
          <!--<apex:outputField value="{!c.LastModifiedDate}"/>-->
      </apex:column>

      <apex:column width="8%" headerValue="View">
        <apex:outputlink style="color:blue;" value="/apex/QuoteDetail?id={!c.Id}">View Detail</apex:outputLink>
      </apex:column>

      <apex:column width="5%" headerValue="Edit">
        <apex:outputlink style="color:blue;" value="/apex/QuoteGroupCreate?id={!c.Id}">Edit</apex:outputLink>
      </apex:column>
  </apex:pageBlockTable>

marked as duplicate by Himanshu, Dave Humm, martin, Markus Slabina, Eric apex Sep 8 '17 at 9:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    Short answer is - use pagination and make container of total quotes as transient. It this case all quotes would not be in view state – Oleksandr Berehovskyi Sep 8 '17 at 7:48
1

Work through your code and see which ones can be marked as transient. This will exclude them from view state.

 private transient  List<Quote> pageQuotes;

Below is the full working code of your page Re-modified. few Changes i have did both on your visual page and controller. I guess no need more explanation your code.

VisualPage :

<apex:page controller="MyPagingController" tabStyle="Quote"> 
    <apex:sectionHeader title="List of Quotes"></apex:sectionHeader> 
    <apex:form > 
        <apex:pageBlock title="Search Quote"> 
            <apex:outputLabel style="font-weight:Bold;" value="Quote Name : " /> 
            <apex:inputText value="{!searchQuoteName}" /> 

            <apex:outputLabel style="font-weight:Bold;" value="Quote Number : " /> 
            <apex:inputText value="{!searchQuoteNumber}" /> 
            <br/><br/> 

            <apex:commandButton value="Search" action="{!Search}" reRender="pageBlock"></apex:commandButton> 
        </apex:pageBlock> 
    </apex:form> 
    <apex:form > 
        <apex:pageBlock title="List of Quotes" id="pageBlock"> 
            <apex:pageBlockButtons location="top" dir="LTR" > 
                <apex:commandButton value="Create New Quote" action="/apex/QuoteGroupCreate?editmode=False" /> 
            </apex:pageBlockButtons> 


            <apex:pageBlockTable value="{!quotes}" var="c" rendered="{!NOT(ISNULL(quotes))}" rows="{!PageSize}"> 

                <apex:column width="15%"> 
                    <apex:facet name="header"> 
                        <apex:commandLink action="{!ViewData}" value="Quote Name{!IF(sortExpression=='name',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort"> 
                            <apex:param value="name" name="column" assignTo="{!sortExpression}" ></apex:param> 
                        </apex:commandLink> 
                    </apex:facet> 
                    <apex:outputlink value="/apex/QuoteDetail?id={!c.Id}">{!c.name}</apex:outputlink> 
                </apex:column> 

                <apex:column width="35%" headerValue="Opportunity Name"> 
                    <apex:outputlink value="/{!c.OpportunityId}" target="_blank">{!c.Opportunity.Name}</apex:outputlink> 
                </apex:column> 

                <apex:column width="10%" value="{!c.QuoteNumber}"> 
                    <apex:facet name="header"> 
                        <apex:commandLink action="{!ViewData}" value="Quote Number{!IF(sortExpression=='QuoteNumber',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdNumberSort"> 
                            <apex:param value="QuoteNumber" name="column" assignTo="{!sortExpression}" ></apex:param> 
                        </apex:commandLink> 
                    </apex:facet> 
                </apex:column> 

                <apex:column width="10%" headerValue="Quote Amount" value="{!c.GrandTotal}"/> 

                <apex:column width="15%" value="{!c.createdDate}"> 
                    <apex:facet name="header"> 
                        <apex:commandLink action="{!ViewData}" value="Date{!IF(sortExpression=='createdDate',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdCreatedAtSort"> 
                            <apex:param value="createdDate" name="column" assignTo="{!sortExpression}" ></apex:param> 
                        </apex:commandLink> 
                    </apex:facet> 
                </apex:column> 

                <apex:column width="35%" headerValue="Created By"> 
                    <apex:outputField value="{!c.createdById}"/> 
                    <!--<apex:outputField value="{!c.createdDate}"/>--> 
                </apex:column> 

                <apex:column width="35%" headerValue="Modified By"> 
                    <apex:outputField value="{!c.LastModifiedById}"/> 
                    <!--<apex:outputField value="{!c.LastModifiedDate}"/>--> 
                </apex:column> 

                <apex:column width="8%" headerValue="View"> 
                    <apex:outputlink style="color:blue;" value="/apex/QuoteDetail?id={!c.Id}">View Detail</apex:outputLink> 
                </apex:column> 

                <apex:column width="5%" headerValue="Edit"> 
                    <apex:outputlink style="color:blue;" value="/apex/QuoteGroupCreate?id={!c.Id}">Edit</apex:outputLink> 
                </apex:column> 
            </apex:pageBlockTable> 
            <div align="right" style="display:{!IF(quotes.size > 0,'block','none')}"> 
                <br/> 
                <font size="1pt">Page #:&nbsp;<apex:outputLabel value="{!PageNumber}"/>&nbsp;out of&nbsp;<apex:outputLabel value="{!totalPageNumber}"/>&nbsp;&nbsp;&nbsp;&nbsp;</font> 
                <apex:commandButton value="Previous" action="{!previous}" disabled="{! NOT(hasPrevious)}" reRender="pageBlock" ></apex:commandButton> 
                <apex:commandButton value="Next" action="{!next}" reRender="pageBlock" disabled="{! NOT(hasNext)}" ></apex:commandButton> 
            </div> 
        </apex:pageBlock> 
    </apex:form> 
</apex:page>

Controller :

public class MyPagingController{
    public transient List<Quote> quotes{get;private set;}

    private String sortDirection = 'DESC';
    private String sortExp = 'createdDate';
    public final decimal pageSize {get;set;} // Modified by Nail David because pageSize is unknown property for visualforce page
    public Integer totalPageNumber{get;private set;}
    public String searchQuoteName { get; set; }
    public String searchQuoteNumber { get; set; }

    public ApexPages.StandardSetController setCon{get;set;}

    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }

    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }


    public void previous() {
        setCon.previous();
        quotes= (List<quote>)setCon.getRecords();    
    }

    public void next() {
        setCon.next();
        quotes= (List<quote>)setCon.getRecords();        
    }

    public String sortExpression    {
        get 
        {
            return sortExp;
        } 
        set
        {
            if (value == sortExp)
                sortDirection = (sortDirection == 'ASC')? 'DESC' : 'ASC';
            else
                sortDirection = 'ASC';
            sortExp = value;
        }
    }

    public String getSortDirection()    {
        if (sortExpression == null || sortExpression == '')
            return 'ASC';
        else
            return sortDirection;
    }

    public void setSortDirection(String value)    {  
        sortDirection = value;
    }

    public MyPagingController()  {
        pageSize = 20; // Added by Nail David
        string queryString = 'Select Id, Name, Opportunity.Name, QuoteNumber, TotalPrice, CreatedDate, GrandTotal, CreatedById, LastModifiedById from Quote';
        setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
        setCon.setPageSize((Integer)pageSize);
        quotes= (List<quote>)setCon.getRecords();    
        totalPageNumber=(Integer)  (setCon.getResultSize()/pageSize).round(System.RoundingMode.CEILING);
    }

    public PageReference ViewData()
    {   
        BindData();        
        return null;
    }

    private void BindData()
    {
            string sortFullExp = sortExpression  + ' ' + sortDirection;            
            string searchQuoteName = searchQuoteName;
            String searchQuery = '';
            String s = '';
            String squote = '';

            if(searchQuoteName != null){
                s = '\'%' + searchQuoteName + '%\''; 
                searchQuery = ' WHERE Name LIKE '+s; 
            }

            if(searchQuery != ''){
                if(searchQuoteNumber != null){
                    squote = '\'%' + searchQuoteNumber + '%\''; 
                    searchQuery += ' AND QuoteNumber LIKE '+squote; 
                }    
            }else{
                if(searchQuoteNumber != null){
                    squote = '\'%' + searchQuoteNumber + '%\''; 
                    searchQuery = ' WHERE QuoteNumber LIKE '+squote; 
                }
            }

        string queryString = 'Select Id, Name, Opportunity.Name, QuoteNumber, TotalPrice, CreatedDate, GrandTotal, CreatedById, LastModifiedById from Quote '+searchQuery +' order by ' +sortFullExp+ ' Limit 10000';
        System.debug('query *******' + queryString);
        setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));       
        setCon.setPageSize((Integer)pageSize);
        quotes= (List<quote>)setCon.getRecords();        
        totalPageNumber=(Integer)  (setCon.getResultSize()/pageSize).round(System.RoundingMode.CEILING);
    }

    public PageReference Search() {
        BindData();
        return null;
    }
}
  • quotes to send to view page should have public getter and shouldn't be transient. – Oleksandr Berehovskyi Sep 8 '17 at 7:54
  • @NITHESHK but it still show me same size limit, is that correct ? – Nail David Sep 8 '17 at 8:55
  • @NailDavid can you post me both vf code also . so i can understand which one is need in vf page – NITHESH K Sep 8 '17 at 9:11
  • @NITHESHK updated my question and added vf page's pageblock table – Nail David Sep 8 '17 at 9:14
  • @NailDavid You wanted to do search pagination over a Quotes right ? – NITHESH K Sep 8 '17 at 9:31

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