Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 30 · Projects

Project: Order Export to CSV

Add an Export CSV bulk action to the PrestaShop orders grid: a Symfony route, permission checks, a streamed CSV and safe cell values, with runnable stand-ins.

Merchants constantly ask for "the orders as a spreadsheet". PrestaShop's back office has a built-in export for some grids, but a custom export lets you choose the columns, format the money, and send the file to the accounting team the way they want it. This project builds one in the modern way: a Symfony back office route, a bulk action added to the orders grid, a CSV that is streamed instead of built in memory, and permission checks so only the right employees can download customer data.

PrestaShop cannot run on this site, so the module code, YAML and hook methods below are read-only. Each part has a runnable plain-PHP stand-in that is not PrestaShop code but follows the same logic. The real classes and attribute names differ slightly between PrestaShop 8 and 9, so check them against the version you target.

What you will build

flowchart LR
    G["Orders grid"] --> S["Select orders<br/>bulk action: Export CSV"]
    S --> R["POST to route<br/>acme_orderexport_export"]
    R --> A{"Employee allowed<br/>to read orders?"}
    A -->|"no"| X["Access denied"]
    A -->|"yes"| Q["Load rows in chunks"]
    Q --> W["Write CSV rows<br/>as they are produced"]
    W --> F["Browser downloads<br/>orders.csv"]

The file is written to the response in pieces, so memory use stays flat for 10 or 10,000 orders.

The module is orderexport:

TEXT
modules/orderexport/
  orderexport.php
  composer.json
  config/routes.yml
  config/services.yml
  src/Controller/Admin/ExportController.php
  src/Export/OrderCsvExporter.php
  index.php

Step 1: register the bulk action

The orders page is a grid, and every grid fires a hook named after its definition so modules can change it. For orders, the hook is actionOrderGridDefinitionModifier. Your module adds a bulk action that submits the selected order ids to a route.

PHP
<?php
use PrestaShop\PrestaShop\Core\Grid\Action\Bulk\Type\SubmitBulkAction;
use PrestaShop\PrestaShop\Core\Grid\Definition\GridDefinitionInterface;

class OrderExport extends Module
{
    public function __construct()
    {
        $this->name = 'orderexport';
        $this->tab = 'administration';
        $this->version = '1.0.0';
        $this->author = 'Acme';
        $this->need_instance = 0;
        $this->ps_versions_compliance = ['min' => '8.0.0', 'max' => _PS_VERSION_];
        parent::__construct();

        $this->displayName = $this->trans('Order export', [], 'Modules.Orderexport.Admin');
        $this->description = $this->trans('Export selected orders as CSV.', [], 'Modules.Orderexport.Admin');
    }

    public function install(): bool
    {
        return parent::install() && $this->registerHook('actionOrderGridDefinitionModifier');
    }

    public function hookActionOrderGridDefinitionModifier(array $params): void
    {
        /** @var GridDefinitionInterface $definition */
        $definition = $params['definition'];

        $definition->getBulkActions()->add(
            (new SubmitBulkAction('acme_export_orders'))
                ->setName($this->trans('Export as CSV', [], 'Modules.Orderexport.Admin'))
                ->setOptions(['submit_route' => 'acme_orderexport_export'])
        );
    }
}

The route name acme_orderexport_export ties the button to the controller you define next. Prefix it with your vendor name so it cannot clash with another module's route.

Step 2: the route and the controller

Routes for module controllers live in config/routes.yml and are loaded automatically when the module is enabled. The _legacy_controller default tells the permission system which back office section the page belongs to; it should be one the employee profile already knows, here the orders page.

YAML
acme_orderexport_export:
  path: /acme/orders/export
  methods: [POST]
  defaults:
    _controller: 'PrestaShop\Module\OrderExport\Controller\Admin\ExportController::exportAction'
    _legacy_controller: AdminOrders

The controller extends PrestaShop's admin controller base class, checks permission, reads the selected ids, and returns a StreamedResponse.

PHP
<?php
namespace PrestaShop\Module\OrderExport\Controller\Admin;

use PrestaShop\Module\OrderExport\Export\OrderCsvExporter;
use PrestaShopBundle\Controller\Admin\PrestaShopAdminController;
use PrestaShopBundle\Security\Attribute\AdminSecurity;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ExportController extends PrestaShopAdminController
{
    #[AdminSecurity("is_granted('read', 'AdminOrders')", message: 'You cannot export orders.')]
    public function exportAction(Request $request, OrderCsvExporter $exporter): Response
    {
        $ids = array_filter(array_map('intval', (array) $request->request->all('order_orders_bulk')));
        if ($ids === []) {
            $this->addFlash('error', 'Select at least one order.');
            return $this->redirectToRoute('admin_orders_index');
        }

        $response = new StreamedResponse(function () use ($exporter, $ids): void {
            $exporter->write(fopen('php://output', 'wb'), $ids);
        });
        $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
        $response->headers->set('Content-Disposition', 'attachment; filename="orders.csv"');

        return $response;
    }
}

Several details here depend on your PrestaShop version, so confirm them in the core source and the developer documentation for your release:

  • The base controller class and the security annotation. Older 8.x versions use FrameworkBundleAdminController and the @AdminSecurity(...) docblock annotation; newer versions use the class and PHP attribute shown above.
  • The name of the submitted field. Grid bulk actions post the selected ids under a key built from the grid id; inspect a real bulk request in the browser's network tab to see it, then read that exact key.
  • The name of the orders list route used in redirectToRoute.

The service file registers the exporter so Symfony can inject it:

YAML
services:
  _defaults:
    autowire: true
    public: true

  PrestaShop\Module\OrderExport\:
    resource: '../src/*'

Whatever the version, three rules stay the same. Check the employee's right before doing any work. Treat the ids as untrusted input and cast them to integers. And never put customer data in a response without a permission check, because an order export is a list of names, addresses and emails.

A stand-in for the permission check

The first stand-in shows the decision the security attribute makes: an employee profile maps sections to the rights it has, and the action is refused unless the right is present.

PHP Permission check before the export runs

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the dirty ids abc, -3 and 0 disappear and the duplicate 14 collapses, so the query never sees garbage.

Step 3: stream the CSV

A shop can have thousands of orders. Building the whole file as one string would use memory in proportion to the size and could hit PHP's limit. A StreamedResponse calls your function while the response is being sent, and you write one row at a time. Load the data in chunks so memory stays flat.

PHP
<?php
namespace PrestaShop\Module\OrderExport\Export;

class OrderCsvExporter
{
    private const CHUNK = 200;

    public function write($handle, array $orderIds): void
    {
        fwrite($handle, "\xEF\xBB\xBF"); // UTF-8 byte order mark so Excel reads accents correctly
        fputcsv($handle, ['Reference', 'Date', 'Customer', 'Total', 'Currency', 'Status'], ',', '"', '');

        foreach (array_chunk($orderIds, self::CHUNK) as $chunk) {
            $in = implode(',', array_map('intval', $chunk));
            $rows = \Db::getInstance()->executeS(
                'SELECT o.reference, o.date_add, CONCAT(c.firstname, " ", c.lastname) AS customer,
                        o.total_paid_tax_incl AS total, cur.iso_code AS currency, o.current_state
                 FROM `' . _DB_PREFIX_ . 'orders` o
                 JOIN `' . _DB_PREFIX_ . 'customer` c ON c.id_customer = o.id_customer
                 JOIN `' . _DB_PREFIX_ . 'currency` cur ON cur.id_currency = o.id_currency
                 WHERE o.id_order IN (' . $in . ')
                 ORDER BY o.id_order'
            );

            foreach ($rows as $row) {
                fputcsv($handle, $this->safeRow($row), ',', '"', '');
            }
        }
    }

    private function safeRow(array $row): array
    {
        return array_map(static function ($value): string {
            $text = (string) $value;
            // spreadsheet formula injection: a cell starting with = + - @ would be run as a formula
            return $text !== '' && strpbrk($text[0], "=+-@\t\r") !== false ? "'" . $text : $text;
        }, $row);
    }
}

A real exporter would show the order status name instead of its numeric id (join order_state_lang for the employee's language) and would use the shop's money formatting rules; see Working with Products, Carts and Orders. Money in the database is stored as decimals; if you build an accounting export for another system, read Money as Integers first.

Why the quote in front of some cells?

A customer can type anything in their name field, including =HYPERLINK("http://evil.example", "Click"). When an employee opens your CSV in a spreadsheet program, a cell that begins with =, +, - or @ may be executed as a formula. This is called CSV (or formula) injection. Prefixing such cells with an apostrophe makes the spreadsheet treat them as text. It is a cheap defence for a file that contains user-supplied values.

A stand-in for the exporter

The second stand-in writes the same CSV from SQLite data. It reads in chunks of two rows, so you can see the streaming shape, writes to an in-memory stream, and applies the formula guard. The PHP 8.4+ rule to pass the escape argument explicitly to fputcsv is followed here, too.

PHP Chunked CSV export with a formula guard

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the second and fourth data rows. The dangerous names start with an apostrophe, the name with a comma and quotes is wrapped and escaped correctly by fputcsv, and the money has a fixed decimal point so every program parses it the same way. Note that the apostrophe guard also changes legitimate values such as a negative number -2; if you export numeric columns, write numbers as numbers and apply the guard only to free-text fields.

Step 4: test it like a user

  1. Install the module and open the orders page; select two orders and check that the bulk action appears.
  2. Log in as an employee whose profile has no right on orders, try the same route and confirm you are refused (use a second browser profile).
  3. Export an order whose customer name starts with = and open the file in a spreadsheet.
  4. Export 5,000 orders in a test shop and watch PHP's memory use; with chunks it should stay roughly flat.

Automated checks belong on the exporter class: it takes a handle and ids, so you can test the formatting with an in-memory stream without a browser, the approach from Testing Modules.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does the controller return a StreamedResponse?

    A streamed response runs your callback while sending, so you never hold the whole file in memory.
  2. 2. What should happen before the exporter queries any order?

    An export is a list of personal data. The permission check comes first, then input cleaning, then the query.
  3. 3. Why prefix cells that start with =, +, - or @ with an apostrophe?

    A value like =HYPERLINK(...) typed by a customer could execute in the employee's spreadsheet. The apostrophe makes it plain text.
  4. 4. Why are the order ids cast to integers and read in chunks?

    Casting turns untrusted ids into safe numbers, and smaller batches keep each query and the memory use bounded.

Summary

  • Add a bulk action to a grid in actionOrderGridDefinitionModifier, pointing at a prefixed route name.
  • A Symfony admin route checks the employee's right first, then cleans the ids, then streams the file.
  • Write the CSV row by row from chunked queries; add a byte order mark for Excel and pass fputcsv its escape argument explicitly.
  • Defend spreadsheets against formula injection in free-text cells.
  • Class and attribute names differ between PrestaShop 8 and 9, so confirm them against your version.

Next, a project that touches money and order creation: Project: A Simple Payment Gateway Module.