Jump to:

17452 Posts in 4473 Topics by 1971 members

Archive

SilverStripe Forums » Archive » outputting a table as csv

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

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

Page: 1
Go to End
Author Topic: 1842 Views
  • Nicolaas
    Avatar
    Forum Moderator
    213 Posts

    outputting a table as csv Link to this post

    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

  • Sean
    Avatar
    Forum Moderator
    921 Posts

    Re: outputting a table as csv Link to this post

    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

    1842 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.