Jul 04

october cms export CSV

The best solution would be to just add your own controller action to export data.

In toolbar add a new button which will point to your controller's action

Add this `button code` in yout `toolbar` or other place.
        const status = 'active';// use selector to get value $('#statusFilter').val();
        window.location = `<?= Backend::url('hardik/sotest/items/export') ?>/${status}`;
    class="btn btn-primary oc-icon-sign-out"

Note: Please replace author name/plugin name and controller name as per your need in the URL. If you do not need to pass any filter values you can directly use a href link.

Controller side.

Code logic in controller for `preparing CSV` file and `push to download`.
//..some code

use LeagueCsvWriter as CsvWriter;
use OctoberRainParseLeagueEscapeFormula as CsvEscapeFormula;

class Items extends Controller
    //.. some code

    // CUSTOM CSV EXPORT logic
    // only write $status param if you intend to pass it for filters
    // you can add much more filter if you need
    public function export($status) 
        // dd($status); -> O/P => active
        // $status will have value which was passed while calling URL as param
        // now use this to filter your data
        // you can add as many params you need

        // file name when you download CSV
        $fileName = 'export.csv';

        // prepare CSV writer
        $csv = CsvWriter::createFromFileObject(new SplTempFileObject);
        $formatter = new CsvEscapeFormula();

        // add headers as per your need
        $csv->insertOne(['Name', 'Flower']);

        // add records
        // here I added some demo data you need to fetch from DB or something
        // probabally use $results = <<fetch data>>
        $results = [
            'name' => 'First Name',
            'flower' => 'Rose'
            'name' => 'Second Name',
            'flower' => 'Lavender'

        // loop through your records and add to csv rows
        foreach ($results as $result) {
            // formate data and escape quotes etc
            $data = $formatter($result);

            // add single record to CSV
              $data['name'], // this will be name
              $data['flower'] // this will be flower

        // Save for download
        $csvName = uniqid('hs');
        $csvPath = temp_path().'/'.$csvName;
        $output = $csv->__toString();
        File::put($csvPath, $output);

        // download it
        return Response::download($csvPath, $fileName)->deleteFileAfterSend(true);
Note: In this example I added demo data for the generic purpose you can replace it and use your `own data source` and loop through them and add them to the CSV file.

Now when you click on the Export button it will let you download the export.csv file. and its content will be as below.


Please add comments if you need anything more specialized export tutorial.