I have tried this code in Magento 2.3.4
- created events.xml in DaplShortdurabilityetcadminhtml
2.created Productsaveafter.php in DaplShortdurabilityObserver.
<?php
namespace DaplShortdurabilityObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoCatalogModelResourceModelProductAction;
use MagentoCatalogInventoryModelStockStockItemRepository;
class Productsaveafter implements ObserverInterface
{
private $action;
private $stockItemRepository;
public function __construct(
StockItemRepository $stockItemRepository,
Action $action
)
{
$this->action = $action;
$this->stockItemRepository = $stockItemRepository;
}
public function execute(MagentoFrameworkEventObserver $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.
2
Answers
It’s because you are using catalog_product_save_after. So on product save you are again saving and again this event called so bottleneck happens. I would suggest using a different event. Or use catalog_product_save_before event and just set the
$_product->setSku("testNew1")
; and not save $product object.