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;
}
As you can see in
/atk4/csvgithub 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:
or if you want fully featured solution then you can add this trait to your data model:
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.