Ad

Octobercms Export With Dynamic FileName

- 1 answer

I've been using Octobercms for a while and have read documentation about exporting data as csv. However nothing is mentioned a single thing about exporting file with a dynamic name because I needed to append text or set a filename with a date. Is this a sort of limitation with Octobercms?

Ad

Answer

For this, you need to override the default behavior.

In your controller where you added Backend.Behaviors.ImportExportControllerImportExport Behavior, you can add the download method, and there you can change the name of downloading the CSV file.

class YourController extends Controller
{
    public $implement = [
        'Backend.Behaviors.FormController',
        'Backend.Behaviors.ListController',
        'Backend.Behaviors.ImportExportController' // HERE
    ];

    public function download($name, $outputName = null) // <-- THIS method
    {
        $this->pageTitle = $this->pageTitle
            ?: Lang::get($this->asExtension('ImportExportController')
                     ->getConfig('export[title]', 'Export records'));

        // $newOutputName = 'my_new_name.csv'; // <-- HERE you can update name of CSV file
        $outputName = explode('.', $outputName)[0];
        $outputName = $outputName . '-' . date('d-m-Y') . '.csv';
        $newOutputName = $outputName;
        return $this->asExtension('ImportExportController')
                     ->exportGetModel()->download($name, $newOutputName);
    }

    //     ... other code

}

to append date to existing name

// $outputName its coming from the config
$outputName = explode('.', $outputName)[0];
$outputName = $outputName . '-' . date('d-m-Y') . '.csv';
$newOutputName = $outputName;

if any doubt please comment.

Ad
source: stackoverflow.com
Ad