Magento2 Create Order CSV in Var Folder After Order Is Placed

Hello Guys,
If you want to create a order csv with order details after an order is placed only on success action of orders, you can use the following code snippet with small module we have developed.
The following code sample is converted to small extension so you can use it directly in your website. You can also download the module zip by clicking here.

Step 1: Create the module registration php file as registration.php.

Location: app/code/Magemeta/OrderExport/registration.php

<?php
/**
 * Magemeta_OrderExport
 *
 * @category  Magemeta
 * @package   Magemeta_OrderExport
 * @author    Magemeta Development Team <info@magemeta.com> *
 */
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magemeta_OrderExport',
    __DIR__
);

Location: app/code/Magemeta/OrderExport/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magemeta_OrderExport" setup_version="1.0.0"></module>
</config>

Location: app/code/Magemeta/OrderExport/composer.json

{
    "name": "magemeta/module-orderexport",
    "description": "This module is used for creating order csv in var/orderexport folder after an order has been placed.",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "info@magemeta.com",
            "name": "Magemeta"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magemeta\\OrderExport\\": ""
        }
    }
}

Step 2:To create a custom order csv after an order is placed on success action in Magento 2, we need to add the order success action event in events.xml on following location.
Location: app/code/Magemeta/OrderExport/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_onepage_controller_success_action">
        <observer name="magemeta_orderexport_order_success"          
        instance="Magemeta\OrderExport\Observer\CreateOrderObserver" />
    </event>
</config>

Step 3:Lastly we need to add business logic to create csv and put inside the var/orderexport folder.
Location: app/code/Magemeta/OrderExport/Observer/CreateOrderObserver.php

<?php

namespace Magemeta\OrderExport\Observer;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\File\Csv;
use Magento\Sales\Model\OrderFactory;

/**
 * Class CreateOrderObserver
 * @package Magemeta\OrderExport\Observer
 */
class CreateOrderObserver implements ObserverInterface
{
    /**
     * @var DirectoryList
     */
    private $directoryList;
    /**
     * @var Csv
     */
    private $csvProcessor;
    /**
     * @var FileFactory
     */
    private $fileFactory;
    /**
     * @var OrderFactory
     */
    private $orderFactory;

    /**
     * CreateOrderObserver constructor.
     * @param FileFactory $fileFactory
     * @param Csv $csvProcessor
     * @param DirectoryList $directoryList
     * @param OrderFactory $orderFactory
     */
    public function __construct(
        FileFactory $fileFactory,
        Csv $csvProcessor,
        DirectoryList $directoryList,
        OrderFactory $orderFactory
    )
    {
        $this->orderFactory = $orderFactory;
        $this->fileFactory = $fileFactory;
        $this->csvProcessor = $csvProcessor;
        $this->directoryList = $directoryList;
    }

    /**
     * Create an order csv in var/orderexport folder when an order is placed
     *
     * @param EventObserver $observer
     * @return ResponseInterface
     * @throws FileSystemException
     */
    public function execute(EventObserver $observer)
    {
        $orderIds = $observer->getEvent()->getOrderIds();
        $orderId = isset($orderIds[0]) ? $orderIds[0] : null;
        if (!empty($orderId)) {
            $orderModel = $this->orderFactory->create();
            $order = $orderModel->load($orderId);

            $fileName = 'order_' . $orderId . '.csv';
            $filePath = $this->directoryList->getPath(DirectoryList::VAR_DIR)
                . "/orderexport/" . $fileName;

            $orderData = $this->getOrderData($order);
            $this->csvProcessor
                ->setDelimiter(';')
                ->setEnclosure('"')
                ->saveData(
                    $filePath,
                    $orderData
                );
        }
    }

    protected function getOrderData($order)
    {
        $result = [];
        // add header for csv
        $result[] = [
            'orderId',
            'firstname',
            'lastname',
            'email',
            'orderQty',
            'Grandtotal'
        ];

        $incrementId = $order->getIncrementId();
        $firstName = $order->getCustomerFirstname();
        $lastName = $order->getCustomerLastname();
        $email = $order->getCustomerEmail();
        $totalQty = $order->getTotalQtyOrdered();
        $grandTotal = $order->getGrandTotal();

        $result[] = [
            $incrementId,
            $firstName,
            $lastName,
            $email,
            $totalQty,
            $grandTotal
        ];
        return $result;
    }
}

We are done with the custom extension for our order csv creation.

Leave a Reply