0

I am getting this error

Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 143.125KB

I am uploading the files in attachment object and showing them on one VF page and after clicking particular Attachment is should send through email.

public with sharing class InviteFunderWizardController {

    public Loan__c deal {get;set;}
    public list<SyndicatorWrapper> allSyndicators {get;set;}
    public boolean AllSelected {get;set;}
    public Decimal dealPaybackAmt {get;set;}
    public Decimal dealFundingAmt {get;set;}
    public Decimal dealGrossRTR {get;set;}
    public Decimal funderBackendFee {get;set;}
    public Decimal funderUpfrontFee {get;set;}
    public List<Task> tasklist{get;set;}
    public List<AttachmentWrapper> ListAllAttachment{get;set;}
    public ID DealID{get;set;}

    public boolean Available_Percent_Required {get;set;} // To indicate if Available % was not alreayd entered and is required now before Syndication.
    public InviteFunderWizardController(ApexPages.StandardController sc) {
        deal = new Loan__c();
        deal = [select Id, Name, Funding_Date__c, Funding_Amount__c,Payback_Amount__c,Daily_Payment__c,fintechLLC__Legal_Corporate_Name__c,
                Total_Syndication_Percentage__c,COJ__c,Renewal__c,Funder__c,Upfront_Fees__c,funder__r.Name,
                Backend_Fees__c,fintechLLC__Funder_Date__c,fintechLLC__IsInvited__c,Gross_RTR__c from Loan__c where Id = :sc.getId()];
       DealID=sc.getID();

        System.debug('deal ID = : '+deal.id);

        prepareSyndicatorsList();
        prepareAttachmentList();
    }



    public class SyndicatorWrapper{
        public boolean isSelected {get;set;}
        public Account synd {get;set;}
        public boolean hasAValidContact {get;set;}
        public SyndicatorWrapper(Account s){
            this.synd = s;
            this.isSelected = false;
            this.hasAValidContact = false;
            for(Contact c :s.Contacts){
                if(c.email!=null){
                    this.hasAValidContact = true;
                    break;
                }
            }
        }
    }

    public class AttachmentWrapper{
        public boolean isSelectedAttach{get;set;}
        public transient Attachment attach{get;set;}

        public AttachmentWrapper(Attachment attach){    
            this.attach=attach;     
        }
    }


    public void prepareAttachmentList()
    {
        ListAllAttachment=new List<AttachmentWrapper>();

        for(Attachment att:[SELECT Id,Name,Body,ContentType FROM Attachment where ParentId=:deal.id]){

            ListAllAttachment.add(new AttachmentWrapper(att));
        }       

    }



    public void prepareSyndicatorsList()
    {
        allSyndicators = new list<SyndicatorWrapper>(); 
        if(Schema.sObjectType.Account.fields.Name.isAccessible() && Schema.sObjectType.Contact.fields.Name.isAccessible() && Schema.sObjectType.Contact.fields.email.isAccessible())
        {
            for(Account synd: [select Id, name,SP_Fee__c,  (select Id, email, name from Contacts where recordtype.Name IN ('Agent','Client Contact','Employee','Introducer')  order by name) from Account where recordtype.Name IN ('Funder') order by name]){
                System.debug('This is the VAlue in Synd' + synd);

                allSyndicators.add(new SyndicatorWrapper(synd));                        
            }
        }
        sortSyndicators();
    }

    private void sortSyndicators(){
        list<SyndicatorWrapper> validMembers = new list<SyndicatorWrapper>();
        list<SyndicatorWrapper> invalidMembers = new list<SyndicatorWrapper>();
        //Step1: Bifurcate valid and invalid which are alreayd sorted by names.
        for(SyndicatorWrapper sw :allSyndicators){
            if(sw.hasAValidContact){
                validMembers.add(sw);
            }
            else {
                invalidMembers.add(sw);
            }
        }
        //Step1: Merge the two lists that are alreayd sorted by names.
        list<SyndicatorWrapper> sortedlist = new list<SyndicatorWrapper>();
        sortedlist.addAll(validMembers);
        sortedlist.addAll(invalidMembers);
        allSyndicators = sortedlist;
    }


    public void CreateGuestSyndications(){ 

        Integer inviteCount = 0;
        string MCA_Site_URL = '';
            fintechLLC__MCA_Settings__c MCASettings =   fintechLLC__MCA_Settings__c.getinstance('MCA_Site_URL');
        if(MCASettings!=null){
            MCA_Site_URL=   MCASettings.fintechLLC__Value__c;
        }
        try{
            map<id,fintechLLC__Funding__c> guestSyndications = new map<id,fintechLLC__Funding__c>(); //map<AccountId,Syndicator>
            for(SyndicatorWrapper sw : allSyndicators){
                if(sw.isSelected && sw.hasAValidContact){
                    guestSyndications.put(sw.synd.Id,new fintechLLC__Funding__c(fintechLLC__Status__c='Pending',fintechLLC__Deal__c = deal.Id,fintechLLC__Funder__c=sw.synd.Id));
                    inviteCount++;
                }
            }
            if(inviteCount==0){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'Please select atleast one participant.'));
                return ;
            }

            insert guestSyndications.values();
            invite(guestSyndications);
        }
        catch(Exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage()+ex.getLineNumber()));
            return ;
        }
    }

    public PageReference Close()
    {
        try{

          PageReference pageRef = new PageReference('/'+DealID);     
           pageRef.setRedirect(true);
           return pageRef;


        }catch(Exception ex){

          ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage()+ex.getLineNumber()));
           return null;        
        }

        return null;


    }

    public void invite (map<id,fintechLLC__Funding__c> guestSyndications){ 

        string MCA_Site_URL = '';
        string BCCemail='[email protected]';
        MCA_Settings__c MCASettings = MCA_Settings__c.getinstance('MCA_Site_URL');
        tasklist=new List<Task>();
        if(MCASettings!=null){
            MCA_Site_URL= MCASettings.value__c;
        }
        try{
            List<Messaging.SingleEmailMessage> lstEmailMsg = new List<Messaging.SingleEmailMessage>();
            for(SyndicatorWrapper sw : allSyndicators){
                if(sw.isSelected && sw.hasAValidContact){
                    Messaging.SingleEmailMessage emailMsg = new Messaging.SingleEmailMessage();
                    List<String> emailIds = new List<String>();
                    List<String> BccEmailIds=new List<String>();
                    BccEmailIds.add(BCCemail);
                    Id targetContact;
                    if(Schema.sObjectType.contact.fields.email.isAccessible())
                    {
                        for(Contact cc : sw.synd.contacts){
                            if(cc.email!=null){
                             emailIds.add(cc.email);
                              targetContact = cc.Id;
                            }
                        }
                    }


                    List<Messaging.EmailFileAttachment> emailAttachments = new List<Messaging.EmailFileAttachment>();

                        for(AttachmentWrapper AttachWrapper : ListAllAttachment) {

                            if(AttachWrapper.isSelectedAttach){
                                Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                                efa.setFileName(AttachWrapper.attach.Name);
                                efa.setBody(AttachWrapper.attach.Body);
                                efa.setContentType('application/pdf');
                                emailAttachments.add(efa);

                            }

                        }                   

                    emailMsg.setToAddresses(emailIds);
                    emailMsg.setBccAddresses(BccEmailIds);
                    emailMsg.setTargetObjectId(targetContact);
                    emailMsg.setWhatId(guestSyndications.get(sw.synd.Id).Id);
                    emailMsg.setTemplateId([select id from EmailTemplate where DeveloperName = 'New_Funder_Email'].id);
                    emailMsg.SaveAsActivity = False;
                    emailMsg.setFileAttachments(emailAttachments);                  
                    lstEmailMsg.add(emailMsg);

                    system.debug('DealID------->'+DealID);


                    Task t=new task();
                    t.Type = 'Email';
                    t.Status='In Progress';
                    t.WhatId= guestSyndications.get(sw.synd.Id).Id;
                    t.whoId= targetContact ;
                    t.subject='Invitation to invester'+' '+sw.synd.Name;
                    tasklist.add(t);

                }
            }

            Messaging.sendEmail(lstEmailMsg);
            insert tasklist;

            if(deal.fintechLLC__IsInvited__c!=true){

               Date dt=Date.valueOf(system.now());
               deal.fintechLLC__Funder_Date__c=dt;
               deal.fintechLLC__IsInvited__c=true;
               update deal;


            }
        }
        catch(Exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage()+ex.getLineNumber()));
            return ;
        }
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm, 'Invitation has been sent to '+ guestSyndications.size() + (guestSyndications.size()==1?' Funder.':' Funders.') ));
    }

}

Kindly help me in this issue

2

2 Answers 2

4

One way to avoid viewstate issues is to move away from getters/setters for the offending controller variables and replacing with methods. If you need to cache a method's value for multiple uses in the same user transaction, you can save in a transient variable

private transient Foo__c[] foos;  // controller code references this. Not in ViewState
public Foo__c[] getFoos() {  // VF page references this, also not in ViewState
    this.foos = this.foos == null
         ? this.foos
         : [select id, ... from Foo__c where ..];
    return this.foos;
}  
4
  • Those "this" references aren't necessary.
    – sfdcfox
    Commented Jun 7, 2016 at 17:54
  • @sfdcfox ah -- personal style for me -- helps me keep track of whether variable reference is to a locally scoped variable versus an object variable
    – cropredy
    Commented Jun 7, 2016 at 17:57
  • Except shouldn't that mean you write this.foos = this.foos == null...?
    – sfdcfox
    Commented Jun 7, 2016 at 18:00
  • @sfdcfox - as usual, you are right; I don't always adhere to my own conventions due to hurriedness :-(
    – cropredy
    Commented Jun 7, 2016 at 19:36
0

Can you check the view state map and see which variable is taking more kb.

go to the user settings and check the "development mode" and "Show View State in Development Mode". Then go to the page and run the scenario and open the view state map. It will give you the tree of all variables with kb it consumed.

Then declare that variable as static or transient.

5
  • okay but can you tell me how can check that? Commented Jun 7, 2016 at 16:16
  • @Anurag This could be a comment too??
    – Mr.Frodo
    Commented Jun 7, 2016 at 16:18
  • go to the user settings and check the "development mode" and "Show View State in Development Mode". Then go to the page and run the scenario and open the view state map. It will give you the tree of all variables with kb it consumed.
    – Anurag
    Commented Jun 7, 2016 at 16:18
  • @Mr.Frodo I had the same issue and fixed it this way. So though I would post it as an answer
    – Anurag
    Commented Jun 7, 2016 at 16:19
  • @AnuragA Then i guess it would be much better if you provide more detail in your answer like the info you provided in your comment.
    – Mr.Frodo
    Commented Jun 7, 2016 at 16:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .