I am using magento 2.3.5 version. Even though the salable qty of the product is 0 the products still appears on the product listing page. How can we hide the product for which salable qty is 0.
I have followed below approaches.
Approach 1 :-
Created event - (event.xml)
<event name="catalog_block_product_list_collection">
<observer name="custom_stockstatusimprovement_catalog_block_product_list_collection" instance="Custom\StockStatusImprovement\Observer\AddStockStatusToProductCollection" />
</event>
Observer - AddStockStatusToProductCollection.php
<?php
declare(strict_types=1);
namespace Custom\StockStatusImprovement\Observer;
use Magento\Framework\{
Event\Observer,
Event\ObserverInterface
};
use Magento\CatalogInventory\Helper\Stock as StockHelper;
use Magento\InventorySalesAdminUi\Model\GetSalableQuantityDataBySku;
class AddStockStatusToProductCollection implements ObserverInterface
{
/**
* @var StockHelper $stockHelper
*/
protected $stockHelper;
private $getSalableQuantityDataBySku;
/**
* @param StockHelper $stockHelper
*/
public function __construct(
StockHelper $stockHelper,
GetSalableQuantityDataBySku $getSalableQuantityDataBySku
) {
$this->stockHelper = $stockHelper;
$this->getSalableQuantityDataBySku = $getSalableQuantityDataBySku;
}
public function execute(Observer $observer) {
$_productCollection = $observer->getEvent()->getCollection();
if(count($_productCollection) > 0){
foreach ($_productCollection as $_product) {
$salable = $this->getSalableQuantityDataBySku->execute($_product->getSku());
$salableQty = $salable[0]['qty'];
if($salableQty <= 0){
$_productCollection->removeItemByKey($_product->getEntityId());
}
}
}
$observer->getEvent()->setCollection($_productCollection);
// return $_productCollection;
}
}
But with this approach, there is an issue with product count, filter & search.
Approach 2 :-
https://www.rakeshjesadiya.com/apply-custom-conditions-for-product-collection-in-magento-2/
Here I am not sure about how to pass salable qty logic in custom query
Can someone please guide me, how can we achieve the same.
Thanks