0

I have tried this code in Magento 2.3.4

1.created events.xml in Dapl\Shortdurability\etc\adminhtml 2.created Productsaveafter.php in Dapl\Shortdurability\Observer.

<?php
namespace Dapl\Shortdurability\Observer;

    use Magento\Framework\Event\ObserverInterface;
    use Magento\Catalog\Model\ResourceModel\Product\Action;
    use Magento\CatalogInventory\Model\Stock\StockItemRepository;

class Productsaveafter implements ObserverInterface
    {    
    private $action;
    private $stockItemRepository;
   
    public function __construct(
        StockItemRepository $stockItemRepository,
        Action $action
    )
    {
        $this->action = $action;
        $this->stockItemRepository = $stockItemRepository;
     
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct(); 
        $_id = $_product->getId(); // for Id
        $_shortdurability = $_product->getShortdurability();
        $_visibility = $_product->getVisibility();
        $_qty = $this->stockItemRepository->get($_id);
        $quantity = $_qty->getQty();
        if(($_shortdurability == 1) && ($quantity == 0))
        {
            $this->action->updateAttributes([$_id], ['visibility' => 1], 0);
            
        } else {
            $this->action->updateAttributes([$_id], ['visibility' => 4], 0);
            //$this->action->updateAttributes([$_id], ['quantity_and_stock_status' => ['is_in_stock' => 1]], 1);
        }
    }   
}

Hi. I can't use save method to set IsInStock attribute value. Because, it's going to infinite loop. finaly i have tried every set method. But stock status has not changed. i have also tried updateStockItemBySku($sku, $stockItem), updateAttributes([$_id], ['quantity_and_stock_status' => ['is_in_stock' => 1]], 1). please, help me. I have searched about it from google, still i am not able to update IsInStock attribute of product, in Magento 2.3.4.

1 Answer 1

0

try this code :

$_product->setQuantityAndStockStatus(['qty' => $quantity, 'is_in_stock' => 1]);
1
  • I have tried, but this is not working. Please help me, someone. Commented Dec 21, 2021 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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