17488 Posts in 4473 Topics by 1978 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 1753 Views |
-
outputting a table as csv

3 December 2007 at 9:21pm
Hi
Today I had one of these moments, where I really enjoyed using silverstripe... I used simple php and it seemed to work seemlessly with silverstripe.
I added the following function to a page controller:
function ExportDetails() {
if(Permission::check('ADMIN')) {
$result = mysql_query("SHOW COLUMNS FROM Mytable");
$select = 'SELECT ';
while($row = mysql_fetch_array($result)) {
$out .= $row["Field"].", ";
$select .= $row["Field"].", ";
$rowFieldNames[] = $row["Field"];
}
$out .= "ID\r\n";
$select .= " ID FROM Mytable";
$result = mysql_query($select);
while($dataRow = mysql_fetch_array($result)) {
foreach($rowFieldNames as $key=>$value) {
$out .= ''.str_replace(",", "[comma]", $dataRow[$value]).', ';
}
$out .= $row["ID"]."\r\n";
}
header("Content-Type: application/txt");
HTTPResponse::addHeader("Content-disposition", "RegistrationsOn".date("Y-m-d").".csv");
print $out;
exit;
}
else {
Security::permissionFailure($this, 'You must be logged in.');
}
}and all I had to do is to add "ExportDetails" after the url and it works (e.g. mypage/ExportDetails gives the csv output. The only line that does not work is HTTPResponse::addHeader("Content-disposition", "RegistrationsOn".date("Y-m-d").".csv"); - it gives ExportDetails as filename. How can I change this.
I also still have to use the dataobject to retrieve the data rather than good old mysql_query (I just love writing my own sql).
Thank you
Nicolaas
-
Re: outputting a table as csv

3 December 2007 at 9:56pm Last edited: 3 December 2007 10:04pm
Hi there,
If you're using a TableListField, or a sub-class of, you can use something like this:
$table = new TableListField();
... // do stuff
$table->setPermissions(array('export', 'delete', 'print'));
'export' allows CSV exports out of the box in TableListField and sub-classes.
For more information, see the documentation for it here: http://doc.silverstripe.com/doku.php?id=tablelistfield#export
Cheers,
Sean
| 1753 Views | ||
|
Page:
1
|
Go to Top |

