1

I am not able to Access the apex variable in script in vf page . It is showing empty while debugging the code.Hope any ony can help me here.Here is the code below:

VF Page:

       <apex:page controller="TestLogisticsMigrate">
    <apex:form id="test">
        <apex:outputPanel id ="form">
            <script>
            function csvFile(){
                var csvData = '{!csvLogisticsData}'
                console.log('csvData '+csvData);
                if(csvData==''){
                    console.log('no data');
                }
                else{
                    console.log('csvData '+csvData);
                    var csvLink = document.createElement('a');
                    csvLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData);
                    csvLink.target = '_blank';
                    csvLink.download = 'LogisticsCharges.csv';
                    csvLink.click();
                }
                
            }
            
            </script>
        </apex:outputPanel>
        <apex:commandButton value="Download CSV"  action="{!migrateRecords}" oncomplete="csvFile();" rerender="form"/>
        
    </apex:form>
    
</apex:page>

Apex Class:

public class TestLogisticsMigrate {
    public String csvLogisticsData{get;set;}
    public void migrateRecords(){
        csvLogisticsData ='';
        Map<String, Schema.SObjectField> schemaFieldMap = Schema.SObjectType.Logistics_Charges__c.fields.getMap();
        List <String> listOfLogisticsFields = new List <String>();
        List <String> listOfLogisticsFieldsForHeader = new List <String>();
        for (String fieldName: schemaFieldMap.keySet()) {
            Schema.DescribeFieldResult dfr =schemaFieldMap.get(fieldName).getDescribe();
            if(dfr.isCustom()){
                if(String.valueOf(schemaFieldMap.get(fieldName).getDescribe().getType()) == 'REFERENCE'){
                    fieldName = fieldName.removeEnd('c')+'r.Name';
                }
                listOfLogisticsFields.add(fieldName);
            }
        }
        listOfLogisticsFieldsForHeader.addAll(listOfLogisticsFields);
        String logisticsFieldsToQuery = String.join( listOfLogisticsFields, ', ' ); 
        listOfLogisticsFieldsForHeader.add('Quote Name');
        listOfLogisticsFieldsForHeader.add('Opportunity Name');
        String query = 'SELECT (SELECT '+ logisticsFieldsToQuery + ' FROM Logistics_Charges__r),name,opportunity.name FROM quote where recordtype.name = \'logistics\'';
        List<Quote> quotes = Database.query(query);
        for (String fieldName : listOfLogisticsFieldsForHeader) {
            csvLogisticsData += (fieldName.replaceAll('__c','').replaceAll('__r.Name', '').replaceAll('_',' ')).toUppercase()+',';        
        }
        csvLogisticsData += '\\n';
        for (Quote q : quotes) {
            for(Logistics_Charges__c charges : q.Logistics_Charges__r){
                for (String fieldName : listOfLogisticsFields) {
                    
                    //check if field is null or not
                    if(!fieldName.contains('.')){
                        csvLogisticsData += charges.get(fieldName) != null ? String.valueOf(charges.get(fieldName)).escapeCsv() : '';
                    }
                    else{
                        csvLogisticsData += charges.getSObject(fieldName.split('.Name')[0]) != null ? String.valueOf(charges.getSObject(fieldName.split('.Name')[0]).get('name')).escapeCsv() : '';
                    }
                    csvLogisticsData +=',';
                }
                csvLogisticsData+=q.get('name')+',';
                csvLogisticsData+=q.opportunity.name+',';
              //  csvLogisticsData = csvLogisticsData.replaceAll('><script type="text/javascript">  SfdcApp.Visualforce.viewstate.ViewstateSender.sendViewstate(\'https://adanicf--PortsDev.my.salesforce.com\'', '');
                csvLogisticsData += '\\n';
            }
        }
          //renderAsExcel='application/vnd.ms-excel#Account Report.csv';
       // return null;
        system.debug('csvLogisticsData---'+csvLogisticsData);
    }
}
2
  • What does your final System.debug('csvLogisticsData---'+csvLogisticsData); show? Jul 15, 2021 at 10:56
  • It shows a long string of characters having a length of around 2 lakhs of characters,maybe the size of the string is the issue because with string having fewer characters it is working fine. Jul 15, 2021 at 11:03

1 Answer 1

1

Once you have 135k (~1.35lakh) of view state, you'll get a view state exceeded error. Consider calling this function remotely:

public class TestLogisticsMigrate {
    @RemoteAction public static String migrateRecords(){
        String csvLogisticsData;
        ... rest of original code here
        return csvLogisticsData;
    }
}

And in your Visualforce page:

    <script>
        function callMigrateRecords() {
            Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.TestLogisticsMigrate.migrateRecords}',
                function(csvData, event) {
                    var csvLink = document.createElement('a');
                    csvLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData);
                    csvLink.target = '_blank';
                    csvLink.download = 'LogisticsCharges.csv';
                    csvLink.click();
                }
            );
        }
    </script>
    <button onclick="callMigrateRecords(); return false">Download CSV</button>

Error handling not included here, but this should get you started.

1
  • Thank u @sfdcfox for this help, using the above modification I am able to download the CSV file but it is not downloading more than 154 rows in the file. Jul 15, 2021 at 13:28

You must log in to answer this question.

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