0

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.

2

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.

  • Thank you. I will try it and let you know. – Kowsigan Atsayam Feb 13 '20 at 11:53
  • Check my update answer, you can get Order details using that way. Note: Use Factory method instead of objectManager. – Rohit Feb 13 '20 at 12:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.