I need to write a plugin that exports data both in CSV and XLSX formats*. As a base I follow Vojta's plugin code (1) that uses ImportExport backend behavior.
The main plugin controller DataImportExport inherits a import-export Behavior from the Backend that is located in the ImportExportController.
class DataImportExport extends Controller
{
public$implement = [
'Backend.Behaviors.ImportExportController',
];
...
}
It's that Behavior that has methods to export data into CSV file. Yet, if I want to export into XLSX file I am supposed to add corresponding methods into that behavior, namely into the exporting controller by overriding some of its existing methods. Yet, as I do that inside DataImportExport controller, it does not work... as I try/test the export process remains the same as it was prior to that with only CSV...
One seems to be not able to override/extend the backend behavior, namely modules\backend\behaviors\ImportExportController.php.
For example, at the DataimportExport controller I try to override the exportFromList() method of ImportExportController behavior by adding code for the XLSX export -
Yet, no positive change... as I try it.
class DataImportExport extends Controller
{
public $implement = [
'Backend.Behaviors.ImportExportController',
];
public function __construct()
{
parent::__construct();
BackendMenu::setContext('RainLab.User', 'user', $this->action);
// extending the ImportExportController behavior
\Backend\Behaviors\ImportExportController::extend(function($model) {
$model->addDynamicProperty('tagsCache', null);
$model->addDynamicMethod('writeXLSX', function() use ($model) {
});
$model->addDynamicMethod('getTagsAttribute', function() use ($model) {
if ($this->tagsCache) {
return $this->tagsCache;
} else {
return $this->tagsCache = $model->tags()->lists('name');
}
});
});
}
...
// method to override
public function exportFromList($definition = null, $options = [])
{
...
$response = Response::make();
if ($options['export_type'] == 'csv') {
/*
* Response CSV
*/
$response->header('Content-Type', 'text/csv');
$response->header('Content-Transfer-Encoding', 'binary');
$response->header('Content-Disposition', sprintf('%s; filename="%s"', 'attachment', $filename));
$response->setContent((string) $csv);
} else {
// export into xlsx code
}
return $response;
}
}
Note
- Vojta's plugin exports/imports only into/from CSV files.
maybe you should look at https://octobercms.com/plugin/vdomah-excel where you can import and export CSV and Excel files ? The documentation is very well, and i use it on many projects to import datas and it's working well.
best, Lucas