Getting Salable Quantity on Magento2.4 Category Pages
In Magento2.4, displaying salable quantity on category pages requires a strategic approach to avoid using deprecated methods like the object manager. Here’s how you can get the salable quantity and show labels for out-of-stock products without resorting to outdated techniques.
Understanding Salable Quantity in Magento
Salable quantity is the available quantity of a product that can be sold based on various conditions such as stock, backorders, etc. It helps customers know if a product is actually available for purchase.
Getting Salable Quantity on Category Pages
To get the salable quantity in your list.phtml file, you can use the getIsSalable method provided by the catalog product class.
<?php $_product = $block->getProduct(); ?>
<?php $salable = $_product->isSalable(); ?>
The $salable variable will be a boolean indicating whether the product is salable or not. To display this information, you can use conditional statements to show different labels based on the value.
Displaying Out-of-Stock Labels
To display a label for out-of-stock products, you can use the following code snippet:
<?php if (!$salable) { ?>
<span class="stock-label">Out of Stock</span>
<?php } elseif ($_product->getStockItem()->getQty() == 0) { ?>
<span class="stock-label">Last Units</span>
<?php } else { ?>
<span class="stock-label">In Stock</span>
<?php } ?>
This code checks if the product is not salable or if the quantity is zero. If either condition is true, it displays a specific label.
Avoiding Deprecated Methods
It’s crucial to avoid using the object manager in your customizations, as it has been deprecated since Magento2.4. Instead, use proper dependency injection techniques provided by the framework.
To learn more about dependency injection and best practices for Magento2.4 development, I recommend checking out our comprehensive guide on Magento2 Development Best Practices.
Conclusion
Displaying salable quantity on category pages is a common requirement in e-commerce projects. By using the isSalable method and avoiding deprecated methods like the object manager, you can achieve this without compromising performance or security.
Don’t forget to explore our Magento2 Tutorials for more insights into Magento development and stay up-to-date with best practices.
Happy coding!