You need to sign in to do that
Don't have an account?
Krishnan Mishra
How do i download csv file using javascript on my visualforce page?
I have values of my CSV stored in a string variable named 'csv'. Now i want to download the content of this variable with click of button('submit') on page but i don't want to redirect to another page.The best is by using java script.PS: the variable is stored in my component it is not a page.
Controller code:
I have tried to provide only the relevant code, if something irrelevant is present then please ignore that and the values are being inserted in csv variable
Controller code:
public class PaginationForComponent { public PaginationForComponent(){ allContactList = new list<wrapper>(); myOrder = 'desc'; sortField='name'; PageNumber = 1; alphabet = new list<string>{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Others','All'}; RecordsPerPageslist = 10; System.debug('constructor called'); csv=''; } Boolean lstNamePresent=false; public String objName{get;set;} public String fieldNames{get;set;} list<sObject> con = new list<sObject>(); public String alphaSearchConct{get;set;} public string msg {get;set;} public Map<id,Boolean> m = new Map<id,boolean>(); list<sObject> sortedList; public String myOrder{get;set;} // Ascending or Descending order of sorting public String sortField{get;set;} // Field by which sorting should be done public boolean selectAll{get;set;} public list<String> alphabet{get;set;} public list<sObject> cont; public list<wrapper> allContactList{get;set;} public list<wrapper> ct = new list<wrapper>(); public list<String> query; public String csv{get;set;} public ApexPages.StandardSetController stdSetController{ //Instantiating a standard set controller get{ if(stdSetController==null){ //con = Database.query('SELECT '+ fieldNames+' FROM '+ objName );//del it from here update con from script n return allContactList by filling it from there only System.debug('con in ssc is : ' + con); stdSetController = new ApexPages.StandardSetController(con); } stdSetController.setPageSize(RecordsPerPageslist); //Limiting Number of records to be displayed per page System.debug('stdSetController called and fieldNames are : ' + allContactList); return stdSetController; } set; } public void SelectedListContacts(){ // Select contacts and save them in a map for(wrapper wc:allContactList){ m.put(wc.con.id,wc.isSelected); if(wc.isSelected==false){ selectAll=false; } } } public void SelectedAllContacts(){ //To select all contacts in a page System.debug(selectAll); allContactList.clear(); for(sObject c:(list<sObject>)stdSetController.getRecords()){ allContactList.add(new wrapper(c)); } if(selectAll==true){ for(wrapper wc:allContactList){ m.put(wc.con.id,wc.isSelected=true); } } else{ for(wrapper wc:allContactList) m.put(wc.con.id,wc.isSelected=false); } } public String[] getqueryList(){ query = fieldNames.split(','); for(String s:query){ if(s=='lastname'){ lstNamePresent=true; } } } public list<wrapper> getWrapperContacts(){ //List of wrapper class to display in table return allContactList; } public Integer stdSize(){ Integer i = stdSetController.getRecords().size(); return i; } public void docReady(){ con = Database.query('SELECT '+ fieldNames+' FROM '+ objName ); System.debug('docReady con is ' + con); for(sObject c:(list<sObject>)stdSetController.getRecords()) allContactList.add(new wrapper(c)); System.debug('docReady allContactList is ' + allContactList); } public void submit() { Set<id> ids = new set<id>(); for(id i:m.keySet()){ if(m.get(i)==true){ ids.add(i); } } String queryStr = 'SELECT ' + fieldNames + ' FROM ' + objName + ' WHERE id IN :ids'; sObject[] c = Database.query(queryStr); String temp = ''; for(Integer i=0;i<c.size();i++){ for(String s: query){ temp = String.valueOf((c[i].get(s))); // System.debug('before escape csv temp is ' + temp); if(temp!=null){ temp = temp.escapeCsv();} // System.debug('temp after escapeCsv() is ' + temp); csv += temp; // System.debug('str is '+str); csv += ', '; } } } // To convert to CSV file public String getgenerateCSV() { System.debug('csv is :' + csv); return csv; } /*public String[] getqueries(){ System.debug(csvQuery); return csvQuery; }*/ public class wrapper{ public boolean isSelected{get;set;} public sObject con{get;set;} public wrapper(sObject con){ //System.debug('constructor of wrapper class called '); isSelected = false; this.con = con; } } }Component code:
<apex:component controller="PaginationForComponent" allowDml="true"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> function SuccessFailure(msg) { if(msg == '') { window.top.location.reload() } else { alert(msg); } } function cannotFind(msg){ if(msg!=null) alert(msg); } $(document).ready(function(){ funAtLast(); }); </script> <apex:attribute name="objectName" description="The object's name" type="String" required="true" assignTo="{!objName}"/> <apex:attribute name="fieldName" description="Fields to be displayed" type="String" required="true" assignTo="{!fieldNames}"/> <apex:outputPanel id="form"> <apex:actionFunction action="{!docReady}" name="funAtLast" reRender="form,alpha,table,button"/> <style> .bPageBlock .pbBody .dataCol { border:0px; } .bPageBlock .pbBody .labelCol { border:0px; } </style> <!-- <apex:commandButton value="Process" reRender="form,alpha,table,button"/>--> <apex:outputPanel rendered="{!allContactList.size!=0}" id="page"> <!-- For alphabetic search--> <div align="right" > <apex:repeat value="{!alphabet}" var="alph" > <apex:commandLink value="{!alph} " action="{!alphaSearch}" oncomplete="cannotFind('{!msg}');" reRender="table,button" id="cs" >   <style type="text/css"> #cs:hover{ background-color: #b3ffff; } </style> <apex:param name="a" value="{!alph}" assignTo="{!alphaSearchConct}"/> </apex:commandLink> </apex:repeat> </div> <apex:pageBlock id="table"> <!-- To delete selected records--> <apex:commandButton action="{!DelSelected}" value="Delete Selected" oncomplete="SuccessFailure('{!msg}');"/> <!-- Button for csv download --> <apex:commandButton action="{!submit}" value="Download CSV" reRender="none"/> <apex:pageMessages rendered="true" id="Msg"/> <apex:PageBlockTable value="{!WrapperContacts}" var="contacts"> <!-- To Edit and Delete a record --> <apex:column headerValue="Action"> <apex:outputLink value="{!URLFOR($Action[objectName].Edit,contacts.con.id)}"> Edit | </apex:outputLink> <apex:outputLink value="{!URLFOR($Action[objectName].Delete,contacts.con.id)}"> Del | </apex:outputLink> </apex:column> <apex:column > <apex:facet name="header"> <apex:inputCheckbox value="{!selectAll}"> <apex:actionSupport event="onclick" action="{!SelectedAllContacts}" reRender="table"/> </apex:inputCheckbox> </apex:facet> <apex:inputCheckbox value="{!contacts.isSelected}"> <apex:actionSupport event="onclick" action="{!SelectedListContacts}" reRender="none" /> </apex:inputCheckbox> </apex:column> <apex:repeat value="{!queryList}" var="fldNames"> <apex:column > <apex:facet name="header"> <apex:commandLink value="{!fldNames}" action="{!toggleSort}" reRender="table"> <apex:param name="sortField" value="{!fldNames}" assignTo="{!sortField}" /> <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" /> </apex:commandLink> </apex:facet> {!contacts.con[fldNames]} </apex:column> </apex:repeat> </apex:PageBlockTable> </apex:pageBlock> <apex:outputPanel id="button"> <div align = "center" > <!-- To return to first page of records--> <apex:commandButton action="{!first}" value="<<" title="First Page" disabled="{!!HasPrevious}" reRender="table,button"/> <!-- To return to Previous page of records--> <apex:commandButton action="{!previous}" value="Previous" disabled="{!!HasPrevious}" reRender="table,button"/> <!-- To return to next page of records--> <apex:commandButton action="{!next}" value="Next >" disabled = "{!!HasNext}" reRender="table,button"/> <!-- To return to last page of records--> <apex:commandButton action="{!last}" value=">>" title="Last Page" disabled="{!!HasNext}" reRender="table,button"/> <!-- InputText to display current page and to navigate to any page number, At righmost side of page--> <span style="float:right"> <apex:outputLabel value="Page "> </apex:outputLabel> <!-- To navigate to the page--> <apex:InputText value="{!PageNumber}" maxLength="4" size="1"> <apex:actionSupport event="onchange" action="{!NavigateByText}" reRender="table,button"/> </apex:InputText> <!-- The above action support is not working--> <apex:outputLabel value=" of {!TotalPages}"> </apex:outputLabel> </span> <!-- To display a list for number of records to be selected per page--> <span style = "float:left"> <apex:SelectList value="{!RecordsPerPageslist}" size="1" > <apex:selectOptions value="{!RecordsPerPageOptionList}"> </apex:selectOptions> <apex:actionSupport event="onchange" action="{!ChangeNumberOfRecordsPerPage}" reRender="table,button"/> </apex:SelectList> </span> </div> </apex:outputPanel> </apex:outputPanel> </apex:outputPanel> </apex:component>
I have tried to provide only the relevant code, if something irrelevant is present then please ignore that and the values are being inserted in csv variable