Question

Can anyone help How to update product stock quantity when placing an order in Magento 2 programmatically?

I am new to Magento.

I need a sample example.

Was it helpful?

Solution

You can using plugin for update stock after placing order:

/app/code/Vendor/Module/etc/di.xml

<?xml version="1.0" ?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Api\OrderManagementInterface">
        <plugin name="after_place_order_operation" type="Vendor\Module\Plugin\OrderManagement"/>
    </type>
</config>

/app/code/Vendor/Module/Plugin/OrderManagement.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Plugin;

use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderManagementInterface;

/**
 * Class OrderManagement
 */
class OrderManagement
{
    /**
     * @param OrderManagementInterface $subject
     * @param OrderInterface           $order
     *
     * @return OrderInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterPlace(
        OrderManagementInterface $subject,
        OrderInterface $result
    ) {
        $orderId = $result->getIncrementId();
        if ($orderId) {
            //Your custom logic
            $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/Order_Info.log');
            $logger = new \Zend\Log\Logger();
            $logger->addWriter($writer);
            $logger->info(print_r($orderId, true));
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $orderData = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($orderId);
            $orderItems = $orderData->getAllVisibleItems();
            foreach ($orderItems as $orderItems) {
                $logger->info(print_r($orderItems->getData(), true));
            }
        }
        return $result;
    }
}

You can get all details using orderId and add your custom logic in plugin for update stock of products.

I hope it will helpful for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top