Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Archive /

Our old forums are still available as a read-only archive.

Moderators: martimiz, Sean, biapar, Willr, Ingo, simon_w

outputting a table as csv


Reply


2 Posts   1915 Views

Avatar
Nicolaas

Forum Moderator, 213 Posts

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

Avatar
Sean

Forum Moderator, 922 Posts

3 December 2007 at 9:56pm

Edited: 03/12/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: [url]http://doc.silverstripe.com/doku.php?id=tablelistfield#export[/url]

Cheers,
Sean