I need to create a CSV file on every order I receive. How can I do this? Can you guys please suggest me a way to do this or an existing module that does that?
Thanks!
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityYou need to create a small module, which will use event-observer feature of magento. we will put an observer which will get trigger when any order will get placed!
create following files:
app/code/Pawan/GenerateCSV/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Pawan_GenerateCSV',
__DIR__
);
app/code/Pawan/GenerateCSV/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="Pawan_GenerateCSV" setup_version="1.0.0">
</module>
</config>
app/code/Pawan/GenerateCSV/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='sales_order_place_after'>
<observer
name='sales_order_place_after'
instance='Pawan\GenerateCSV\Observer\GenerateCSV'
/>
</event>
</config>
app/code/Pawan/GenerateCSV/Observer/GenerateCSV.php
<?php
namespace Pawan\GenerateCSV\Observer;
use Magento\Framework\Event\ObserverInterface;
class GenerateCSV implements ObserverInterface
{
protected $_objectManager;
private $logger;
private $productFactory;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Psr\Log\LoggerInterface $logger,
\Magento\Catalog\Model\ProductFactory $productFactory
) {
$this->_objectManager = $objectManager;
$this->logger = $logger;
$this->productFactory = $productFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getEvent()->getOrder();
$order_id = $order->getIncrementId();
$this->logger->info($order_id);
$this->logger->info("observer working");
}
}
Explanation: Now you have all Order data in observer class, form here you can get order, product information and can get data in CSV
Hope above will help!
$orderItems = $order->getAllItems();
. in foreach loop , you can get item price, id etc..
foreach ($order->getAllItems() as $item) { $productIds[] = $item->getProductId(); $product_qty[] = $item->getQtyOrdered(); $product_price[] = $item->getPrice(); }
but not able to get the price.
May 25, 2021 at 10:19
Magento\Sales\Api\OrderRepositoryInterface $orderRepository
in your observer and get Order like $order = $this->orderRepository->get($orderId);
sales_order_place_after
observer and get required data in CSV