0

I am using agiletoolkit atk4, and I would like to export grid to CSV file, I am using below code how ever i am facing issue below is the detail:

Code:

$grid->menu->addItem(['Export as CSV..', 'icon' => 'add square'], new \atk4\csv\Export($model))->saveAsCSV('file.csv', ['id', 'name']);

issue: Error: Class 'atk4\csv\Export' not found . meaning unable to find the export library within the agiletoolkit atk4 folder.

I am using this article :https://github.com/atk4/csv

looking for help ?

Note: I have done it in different way below is the detail:


if (isset($_GET['export'])) {
    
    header("Location: exportCSV.php?exportid=".@$_GET['export']);
    exit();
}


$button =$grid->menu->addItem(['Export as CSV..', 'icon' => 'add square']);
$button->on('click', null, function ($b) use($app) {

    return [$app->jsRedirect(['export' =>'export'])];
    //return 'success';
});

in exportCSV.php file

$query = "SELECT id,name,address FROM tableName;";
$result = mysqli_query($conn, $query) or die("database error:". mysqli_error($conn));
$records = array();
while( $rows = mysqli_fetch_assoc($result) ) {
    $records[] = $rows;
}   
if(isset($records)) {   
    $csv_file = "csv_export_".date('Ymd') . ".csv";         
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=\"$csv_file\"");  
    $fh = fopen( 'php://output', 'w' );
    $is_coloumn = true;
    if(!empty($records)) {
      foreach($records as $record) {
        if($is_coloumn) {             
          fputcsv($fh, array_keys($record));
          $is_coloumn = false;
        }       
        fputcsv($fh, array_values($record));
      }
       fclose($fh);
    }
    exit;  
}

1 Answers1

0

As you can see in /atk4/csv github repository - it was never implemented. It only contains readme file and that's all :)

Your solution above doesn't use atk4 models and use plain mysqli connection. It's OK if it works, but if your project relies on atk4 models, then you should probably export atk4 models instead.

To export your data to CSV file you can do something like this:

$records = $grid->model->export();

if(isset($records)) {
  ... here goes your code to save data in CSV file
}

or if you want fully featured solution then you can add this trait to your data model:

<?php
/**
 * Trait for exporting model data as CSV file.
 *
 * Usage:
 *  Add this trait in your model. And then simply use it like this:
 *  $model->exportCSV('filename_without_extension', [fields_to_export]);
 */
trait Trait_ModelExportCSV
{
    // CSV configuration
    public $csv_delimiter = ',';
    public $csv_enclosure = '"';
    public $csv_escape_char = "\\";


    public function exportCSV($filename, $fields = [])
    {
        $fields = $fields ?: array_keys($this->getFields);

        // HTTP header
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=$filename.csv");
        header("Pragma: no-cache");
        header("Expires: 0");

        $output = fopen("php://output", "w");
        fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // add BOM for UTF-8 support

        // save CSV header
        $header = [];
        foreach ($fields as $f) {
            $header[] = $this->getField($f)->getCaption();
        }
        fputcsv($output, $header, $this->csv_delimiter, $this->csv_enclosure, $this->csv_escape_char);

        // save CSV rows
        foreach ($this as $row) {
            $r = [];
            foreach ($fields as $f) {
                $v = $row[$f];

                if ($this->getField($f)->type == 'boolean') {
                    $v = $v === true ? "Y" : "N";
                }

                if ($v instanceof \DateTime) {
                    $v = $v->format('Y-m-d');
                }

                $r[] = $v;
            }
            fputcsv($output, $r, $this->csv_delimiter, $this->csv_enclosure, $this->csv_escape_char);
        }

        // close CSV file
        fclose($output);
        exit;
    }
}

This is for a bit older atk4 version, but you can get idea of how it's done and tweak it to match atk4 version you're using.

DarkSide
  • 3,670
  • 1
  • 26
  • 34