How can show values in bar - GoogleChart/SQL - charts

I need to put the values ​​inside the bar or outside it but I need you to show me the value, I've already seen some examples but the arrays tables have more than one line with the values ​​placed in the hand, but mine connects by SQL
How can I place the values ​​on my bar chart?
A user showed me this answer, but in "var data = google.visualization.arrayToDataTable"
It returns the values ​​in the rows
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Descr', 'Downlink', 'Uplink'],
['win7protemplate', 12, 5],
['S60', 14, 5],
['iPad', 3.5, 12], ]);
http://jsfiddle.net/heennkkee/rekso9t6/
But mine only has 1 line per account that pull this value from MySQL
google.load("visualization", "1", {packages:["barchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['quantidade_demanda','COUNT(Subclasse)'],
<?php
$query = "SELECT COUNT(Subclasse), Subclasse AS quantidade_demanda FROM demandas_portal WHERE Categoria = 'Demanda Ambiental' GROUP BY Subclasse";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)']."],";
}
?>
]);
Would I have to add a new variable? because I only have these options
var options = {
colors: ['#00544d'],
width: 500,
height: 250
};
options.legend = 'none';
var chart = new google.visualization.BarChart(document.getElementById('chart_demanda'));
chart.draw(data,options);
}

if you are referring to displaying annotations on the bars,
you need to add another column to the data table,
using an annotation role...
add the annotation role to the column heading, here...
['quantidade_demanda','COUNT(Subclasse)', {role: 'annotation', type: 'string'}], // <-- add annoation role to column heading
then repeat the column value as a string, here...
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)'].",'".$row['COUNT(Subclasse)']."'],"; // <-- add value of annotation, repeat column value as string
see following snippet...
var data = google.visualization.arrayToDataTable([
['quantidade_demanda','COUNT(Subclasse)', {role: 'annotation', type: 'string'}], // <-- add annoation role to column heading
<?php
$query = "SELECT COUNT(Subclasse), Subclasse AS quantidade_demanda FROM demandas_portal WHERE Categoria = 'Demanda Ambiental' GROUP BY Subclasse";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['quantidade_demanda']."',".$row['COUNT(Subclasse)'].",'".$row['COUNT(Subclasse)']."'],"; // <-- add value of annotation, repeat column value as string
}
?>
]);

Related

3 Google Charts on a page displays nothing

currently I am trying to show 3 Google Charts on a page, but the page is blank, it does not display any of the charts. Originally the 1st chart was displayed, then it worked but ever since I attached the 2nd one (even if I deleted that so only the 1st one would be shown again), the page I have is totally blank and I don't know why.
Could you please help me?
Here is my code (I set the $conn and $_SESSION variables at the top of my page):
EDIT: Here is a picture about the source code in my browser:
[![sourcecode][1]][1] What I don't understand is that it looks like it would expect other values to data1 and data2 and that is why the charts are not displayed...
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load Charts and the corechart package.
google.load('current', callback: drawCharts, {packages:['column', 'pie']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);
// Callback that creates and populates a data table, instantiates the pie chart, passes in the data and draws it.
function drawCharts() {
var data1 = google.visualization.arrayToDataTable([
['Classification', 'Number of assets'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT Classification, count('Classification') as count FROM `assets` GROUP BY Classification ORDER BY FIELD(Classification, 'high', 'medium', 'low')";
}else{
$sql = "SELECT Classification, count('Classification') as count FROM `assets` WHERE Responsible =".$_SESSION['name']." GROUP BY Classification ORDER BY FIELD(Classification, 'high', 'medium', 'low')";
}
$result = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($result)) {
echo "['".$result2['Classification']."',".$result2['count']."],";
}
?>
]);
var data2 = google.visualization.arrayToDataTable([
['Risks', 'Percentage'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT Compliant = (SELECT count('id') FROM `risks` WHERE targetrisk >= residualrisk), Non-compliant = (SELECT count('id') FROM `risks` WHERE targetrisk < residualrisk) FROM risks ";
}else{
$sql = "SELECT Compliant = (SELECT count('id') FROM `risks` WHERE responsible =".$_SESSION['name']." AND targetrisk >= residualrisk), Non-compliant = (SELECT count('id') FROM `risks` WHERE ".$_SESSION['name']." AND targetrisk < residualrisk) FROM risks ";
}
$results = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($results)) {
echo "['".$result2['Compliant']."',".$result2['Non-compliant']."],";
}
?>
]);
var data3 = google.visualization.arrayToDataTable([
['Assets', 'Percentage'],
<?php
if ($_SESSION['user_type'] == 'admin') {
$sql = "SELECT count('Asset_name') as Assets, count(`risks`.`assettag`) as Compliant assets FROM `assets`, `risks` JOIN `assettag` ON `assets`.`Tag` = `risks`.`assettag` ";
}else{
$sql = "SELECT count('Asset_name') as Assets, count(`risks`.`assettag`) as Compliant assets FROM `assets`, `risks` JOIN `assettag` ON `assets`.`Tag` = `risks`.`assettag` AND responsible =".$_SESSION['name']."";
}
$results = mysqli_query($conn,$sql);
while ($result2=mysqli_fetch_array($results)) {
echo "['".$result2['Assets']."',".$result2['Compliant assets']."],";
}
?>
]);
var options1 = {
title: 'Asset classification',
legend: { position: 'none' },
width: 900,
height: 500
};
var options2 = {
title: 'Risk compliance',
legend: { position: 'none' },
width: 900,
height: 500
};
var options3 = {
title: 'Asset compliance',
legend: { position: 'none' },
width: 900,
height: 500
};
var chart1 = new google.visualization.ColumnChart(document.getElementById("columnchart"));
chart1.draw(data1, options1);
var chart2 = new google.visualization.PieChart(document.getElementById("piechart"));
chart2.draw(data2, options2);
var chart3 = new google.visualization.PieChart(document.getElementById("piechart2"));
chart3.draw(data3, options3);
}
</script>
</head>
<body>
<div id="columnchart"></div>
<br>
<div id="piechart" ></div>
<br>
<div id="piechart2" ></div>
</body>
</html>
[1]: https://i.stack.imgur.com/f2u3D.png

Pie chart not showing slice

I create a pie chart using google services. the problem is that i want to show credit and debit in pie chart, but output comes only in one color. Here is my query.
$data = mysqli_query($link, "select SUM(pay_payable) as debit, SUM(pay_paid) as credit from purchasers_payment where p_id = '$pur_id'");
and here is my chart setting.
var data = google.visualization.arrayToDataTable([
['Debit', 'Credit'],
<?php
while($row = mysqli_fetch_array($data))
{
echo "['".$row['debit']."',".$row['credit']."],";
}
?>
]);
var options = {
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
here is mine code output
enter image description here
and i want output like this:
enter image description here
the data format for a PieChart uses rows for each slice
to get two slices, you need two rows of data...
['Label', 'Value'],
['Debit', 10000],
['Credit', 2000]
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Debit', 10000],
['Credit', 2000]
]);
var options = {
is3D: true,
height: 300
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>
try the following php...
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
<?php
while($row = mysqli_fetch_array($data))
{
echo "['Debit',".$row['debit']."],['Credit',".$row['credit']."],";
}
?>
]);

Setting starting value for Google Line Chart dynamically and redrawing chart

I am using the code below to generate a line chart for a projected financial balance. Data is generated from information in a MySQL database. What I would like to be able to do is to have a form with an input field on the page that allows the user to set the starting balance dynamically once the page is loaded, such that the chart is redrawn with the correct starting balance, but I can't work out how to do this:
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Amount', 'type' => 'number')
);
[code to generate data goes here - i.e. calculating a balance for each date in the chart]
$balance = $balance - $monthly - $weekly + $session_total;
$temp = array();
$temp[] = array('v' => (string) $date_display);
$temp[] = array('v' => (string) $balance);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var formatter = new google.visualization.NumberFormat({fractionDigits:2,prefix:'\u00A3'});
formatter.format(data, 1);
var options = {
pointSize: 5,
legend: 'none',
hAxis: { showTextEvery:31 },
series: {0:{color:'2E838F',lineWidth:2}},
chartArea: {left:50,width:"95%",height:"80%"},
backgroundColor: '#F7FBFC',
height: 400
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
Hopefully there's a fairly simple way to refresh the chart when new data is available. It requires a small change to your PHP and a few JavaScript tweaks.
The nice thing about using Google Charts is that you can just re-draw them by calling drawChart() again, you just need to be able to modify the data before you do it.
The change I would make the PHP would be to store the original value, so that when you want to change the value according to the user's input you can always have something to refer back to:
// display the date
$temp[] = array('v' => (string) $date_display);
// the data used by the chart
$temp[] = array('v' => (string) $balance);
// the original value
$temp[] = array('v' => (string) $balance);
I would also make the table data global rather than drawing it directly into the function, this way you can change it and refresh the chart quite easily.
var table = <?php echo $jsonTable; ?>;
function drawChart() {
var data = new google.visualization.DataTable(table);
......
}
I tested this with a basic form that looks like this:
<form method="post" action="#" onsubmit="return false;">
<input type="text" id="balance1" />
<input type="text" id="balance2" />
<button onclick="return refreshChart()">Go</button>
</form>
Clicking on the button cancels the default action and calls a function called refreshChart(). This function takes the value and adds it to the original values on the fly before re-drawing the chart:
function refreshChart() {
var balance1 = document.getElementById('balance1').value;
var balance2 = document.getElementById('balance2').value;
if(!balance1) {
balance1 = 0;
}
if(!balance2) {
balance2 = 0;
}
for(var i = 0, length = table.rows.length; i < length; i++) {
table.rows[i].c['1'].v = parseFloat(table.rows[i].c['2'].v) + parseFloat(balance1) + parseFloat(balance2);
}
drawChart();
return false;
}
It takes the balance entered and adds it to the original value stored in table.rows[i].c['2'].v and overwrites the value in table.rows[i].c['1'].v which is used by the chart. It then calls the original drawChart() function but the new data is used.
I played around with some default data and this is the output I tested it with on JSFiddle.

Moodle moodleform::validation()

In my custom plugin I am simply using three drop down and one text box. When I submit the form and validation($data) method is invoked I just get value of state drop down along with the textbox value.
Value of other two drop downs is not returned. I am not sure what I am missing.
Here is my code:
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->libdir.'/formslib.php');
class ohio_addconfiguration_form extends moodleform {
// Define the form
function definition() {
$id = optional_param('id', 0, PARAM_INT);
$countries = array();
$states = array();
$counties = array();
$cities = array();
$mform =& $this->_form;
// Creating hidden variable id
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
// Creating header "Configuration"
$mform->addElement('header', 'configuration', get_string('ohio', 'local_ohio'));
/* Listing States */
$states_result = $this->get_states("", "1", "id, state_name", "state_name ASC");
if($states_result) {
foreach($states_result as $key=>$state){
$states[$state->id] = $state->state_name;
}
}
$states= count($states)?array(''=>get_string('select_state', 'local_ohio').'...') + $states :array(''=>get_string('select_state', 'local_ohio').'...');
$mform->addElement('select', 'state_id', get_string('select_state', 'local_ohio'), $states);
$mform->addRule('state_id', get_string('required'), 'required', null, 'client');
$mform->setType('state_id', PARAM_INT);
/* Listing Counties */
$counties= array(''=>get_string('select_county', 'local_ohio').'...');
$mform->addElement('select', 'county_id', get_string('select_county', 'local_ohio'), $counties);
$mform->addRule('county_id', get_string('required'), 'required', null, 'client');
$mform->setType('county_id', PARAM_INT);
/* Listing Cities */
$cities= array(''=>get_string('select_city', 'local_ohio').'...');
$mform->addElement('select', 'city_id', get_string('select_city', 'local_ohio'), $cities);
$mform->addRule('city_id', get_string('required'), 'required', null, 'client');
$mform->setType('city_id', PARAM_INT);
// Creating text box for School
$mform->addElement('text', 'school_name', get_string('school_name', 'local_ohio'), 'size="25"');
$mform->setType('school_name', PARAM_TEXT);
$mform->addRule('school_name', get_string('required'), 'required', null, 'client');
$mform->addRule('school_name', get_string('maximumchars', '', 100), 'maxlength', 100, 'client');
$this->add_action_buttons();
}
function validation($data) {
global $DB;
echo "<pre>";
print_r($data);
exit;
}
}
I'm not sure what are you looking for exactly, either form validation or data retrieval, but I'm assuming you're interested in data retrieval and the code you have provided above is written in 'filename_form.php'.
The validation() method is used to validate the data entered in the fields on the server side, and not to get the values of the fields.
To get the values of the fields, you need to create another file named 'filename.php', and include 'filename_form.php' in it for displaying the form.
You can refer here for using Formslib.

Cant export to excel 2010 student edition via Zend Framework

I'm trying to export data to ms excel, I have Office 2010 student edition for my application by following Pablo Viquez's post http://www.pabloviquez.com/2009/08/export-excel-spreadsheets-using-zend-framework/.
However I can't get it working the following happens
1.On entering reports/report/todaysappointmentsreport/format/excel into the address bar the workbook attempts to save as excel.xls
2.When I open the file Excel gives me the following warning: The file you are trying to open 'excel.xls', is in a different format than specified by the file extension verify the file is not corrupt and is from a trusted source before opening the file.
On opening the file all that is shown is the code in my todaysappointmentsreport.export.phtml file
Can anyone tell me where I'm going wrong, as I need to get this working.
I can verify that the query works and the data appears in my todaysappointmentsreport.phtml file on screen. I can also verify that the component is installed in pear along with the OLE component that it is dependent on.
My Controller code
class Reports_ReportController extends Zend_Controller_Action
{
public function init()
{
// Excel format context
$excelConfig =
array('excel' => array
('suffix' => 'excel',
'headers' => array(
'Content-type' => 'application/vnd.ms-excel')),
);
//initalise context switch
$contextSwitch = $this->_helper->contextSwitch();
// Add the new context
$contextSwitch->setContexts($excelConfig);
// Set the new context to the reports action
$contextSwitch->addActionContext('todaysappointmentsreport', 'excel');
$contextSwitch->initContext();
}
// action to redirect user straight to login page
public function preDispatch()
{
// set admin layout
// check if user is authenticated
// if not, redirect to login page
$url = $this->getRequest()->getRequestUri();
if (!Zend_Auth::getInstance()->hasIdentity()) {
$session = new Zend_Session_Namespace('petmanager.auth');
$session->requestURL = $url;
$this->_redirect('/login');
}
}
// report to print todays appointments
public function todaysappointmentsreportAction()
{
$t=date('y-m-d');
$q = Doctrine_Query::create()
->from('PetManager_Model_Groomappointments g')
->leftJoin('g.PetManager_Model_Clients c')
->leftJoin('g.PetManager_Model_Pets p')
->leftJoin('g.PetManager_Model_Users u')
->leftJoin('g.PetManager_Model_Groomservices s')
->leftJoin('s.PetManager_Model_Groomprocedures r')
->where('g.gapmtStatus = 1 AND g.gapmtDate = ?',$t)
->orderBy('g.gapmtSTime,g.gapmtSTime,u.name');
$result = $q->fetchArray();
if (count($result) >= 1) {
$this -> view -> records = $result;
}
}
My todaysappointmentsreport.excel.phtml code as I said this is what appears in the excel file when I open it.
// Change error reporting for compatibility
// Spreadsheet Excel Writter was built using PHP4,
// so there's a lot of DEPRECATED notices
error_reporting(E_ERROR | E_WARNING | E_PARSE);
/**
* PEAR package
*
* #link http://pear.php.net/package/Spreadsheet_Excel_Writer
* #see PEAR/Spreadsheet/Excel/Writer.php
*/
require_once 'Spreadsheet/Excel/Writer.php';
// Lets define some custom colors codes
define('CUSTOM_DARK_BLUE', 20);
define('CUSTOM_BLUE', 21);
define('CUSTOM_LIGHT_BLUE', 22);
define('CUSTOM_YELLOW', 23);
define('CUSTOM_GREEN', 24);
// First, we create a Workbook
$workbook = new Spreadsheet_Excel_Writer();
// Add one sheet, called: Users Report
$worksheet = &$workbook->addWorksheet('Todays Grooming Appointments Report');
// Create the custom colors on our new workbook
// This function takes 4 params:
// - Code index [1 to 64]
// - RGB colors (0-255)
$workbook->setCustomColor(CUSTOM_DARK_BLUE, 31, 73, 125);
$workbook->setCustomColor(CUSTOM_BLUE, 0, 112, 192);
$workbook->setCustomColor(CUSTOM_LIGHT_BLUE, 184, 204, 228);
$workbook->setCustomColor(CUSTOM_YELLOW, 255, 192, 0);
$workbook->setCustomColor(CUSTOM_GREEN, 0, 176, 80);
// Lets hide gridlines
//$worksheet->hideScreenGridlines();
// Lets create some custom styles
$formatHeader = &$workbook->addFormat();
$formatHeader =
&$workbook->addFormat(
array('Size' => 16,
'VAlign' => 'vcenter',
'HAlign' => 'center',
'Bold' => 1,
'Color' => 'white',
'FgColor' => CUSTOM_DARK_BLUE));
$formatReportHeader =
&$workbook->addFormat(
array('Size' => 9,
'VAlign' => 'bottom',
'HAlign' => 'center',
'Bold' => 1,
'FgColor' => CUSTOM_LIGHT_BLUE,
'TextWrap' => true));
$formatData =
&$workbook->addFormat(
array(
'Size' => 8,
'HAlign' => 'center',
'VAlign' => 'vcenter'));
/**
* First, format the worksheet, adding the headers
* and row/columns custom sizes
*/
// Create a nice header with a dark blue background
// The function setRow takes 3 parameters:
// - row index
// - row height
// - Format to apply to row [Optional]
$worksheet->setRow(0, 11, $formatHeader);
$worksheet->setRow(1, 46, $formatHeader);
$worksheet->setRow(2, 11, $formatHeader);
$worksheet->setRow(3, 11, $formatHeader);
$worksheet->setRow(4, 11, $formatHeader);
// Set the size of the columns
// The function setColumn takes 5 params:
// - First column
// - Last column
// - Column Width
// - Format [Optional, default = 0]
// - Hidden [Optional, default = 0]
$worksheet->setColumn(0, 0, 7); // shrink it to 7
$worksheet->setColumn(1, 1, 12); // set the width to 12
$worksheet->setColumn(1, 1, 15); // set the width to 15
$worksheet->setColumn(1, 1, 15); // set the width to 15
$worksheet->setColumn(1, 1, 15); // set the width to 15
/**
*
* Once we have the format ready, add the text to the spreadsheet
*
*/
// Write a text header
$worksheet->write(1, 1, 'Todays Grooming Appointments Report', $formatHeader);
// Create the header for the data starting # row 6
$indexCol = 0;
$indexRow = 6;
$worksheet->write($indexRow, $indexCol++, 'Scheduled Time', $formatReportHeader);
$worksheet->write($indexRow, $indexCol++, 'Client', $formatReportHeader);
$worksheet->write($indexRow, $indexCol++, 'Pet', $formatReportHeader);
$worksheet->write($indexRow, $indexCol++, 'Procedure', $formatReportHeader);
$worksheet->write($indexRow, $indexCol++, 'Groomer', $formatReportHeader);
$indexRow++; // Advance to the next row
$indexCol = 0; // Start # column 0
// Print the report data
if(count($this->records) == 0) {
// No data
$worksheet->write(
$indexRow,
$indexCol,
'No Appointments',
$formatData);
} else {
// Write the data
foreach ($this->records as $r) {
$worksheet->write(
$indexRow,
$indexCol++,
$this->$r['gapmtSTime'] - $this->substr$r['gapmtETime'],
$formatData);
$worksheet->write(
$indexRow,
$indexCol++,
$this->$r['PetManager_Model_Clients']['firstName'] $this->$r ['PetManager_Model_Clients']['lastName'],
$formatData);
$worksheet->write(
$indexRow,
$indexCol++,
$this->$r['PetManager_Model_Pets']['name'],
$formatData);
$worksheet->write(
$indexRow,
$indexCol++,
$this->$r['PetManager_Model_Groomservices']['PetManager_Model_Groomprocedures']['groomprocedure'],
$formatData);
$worksheet->write(
$indexRow,
$indexCol++,
$this->$r['PetManager_Model_Users']['name'],
$formatData);
// Advance to the next row
$indexRow++;
}
}
/**
*
* Response with the excel file
*
*/
// Sends HTTP headers for the Excel file.
$workbook->send('todaysappointmentsreport.xls');
// Calls finalization methods.
// This method should always be the last one to be called on every workbook
$workbook->close();
Ensure the content of your "todaysappointmentsreport.excel.phtml" view file is enclosed in php opening and closing tags.
public function indexAction()
{
$this->filename = "/excel-" . date( "m-d-Y" ) . "-".mt_rand(10000,20000).".xls";
$realPath = realpath($this->filename);
if (false === $realPath )
{
touch($this->filename);
chmod($this->filename, 0777);
}
$this->filename = realpath( $this->filename );
$this->handle = fopen( $this->filename, "w" );
$projectsModul = new Model_DbTable_Projects();
$projects = $projectsModul->fetchProjects();
foreach ($projects->toArray() as $row)
{
$this->finalData[] = array(
$row['id'],
$row['company'],
$row['project'],
$row['start'],
$row['end']
);
}
foreach ( $this->finalData AS $finalRow )
{
fputcsv( $this->handle, $finalRow, "\t" );
}
fclose( $this->handle );
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->getResponse()->setRawHeader( "Content-Type: application/vnd.ms-excel; charset=UTF-8")
->setRawHeader("Content-Disposition: attachment; filename=excel.xls")
->setRawHeader("Content-Transfer-Encoding: binary")
->setRawHeader("Expires: 0")
->setRawHeader("Cache-Control: must-revalidate, post-check=0, pre-check=0")
->setRawHeader("Pragma: public")
->setRawHeader("Content-Length: " . filesize($this->filename))
->sendResponse();
readfile($this->filename);
exit();
}
I'm working on a similar example for my own project so if I discover a resolution I'll update this thread with any results.
There's a helpful article on the contextSwitch view helper here (maltblue) which explains the helper in more depth.
contextswitch view helper
I managed to export to csv ok in the end by putting the headers in the controller action directly as follows.
in my action...
//create the csv file header and filename based on the action name
$actionName = $this->getRequest()->getActionName();
new Admin_Model_Resource_csvFileHeader( $actionName );
rest of code here to get the data to pass to the view file...
the admin model resource is as follows so it can be used by any controller acton...
class Admin_Model_Resource_csvFileHeader
{
private $_csvFileNameFromAction = null;
/**
* Create the first part of the csv file name from the action name
* #param <string> $actionName - name of the controller action for the report
*/
public function __construct( $actionName )
{
$this->_csvFileNameFromAction = $actionName;
$this->generateCsvHeader();
}
/**
* Method is called direct from the constructor
* to centralise and make consistent the csv file header
* so it maximises code re-use
* #return null - just generate the csv header
*/
public function generateCsvHeader()
{
$dateSuffix = date('d-m-Y', time());
$csvFileName = $this->_csvFileNameFromAction.'_'.$dateSuffix;
header('Content-Type: text/x-csv; name="'.$csvFileName.'.csv"');
header('Content-Disposition: inline; filename="'.$csvFileName.'.csv"');
header('Pragma: public');
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header('Content-Transfer-Encoding: none');
}
}