Handling Out-of-Stock Products Effectively in Magento
In this post, we’ll address two common challenges faced by Magento store owners when dealing with out-of-stock products: automatically disabling the product and clearing customers’ carts of unavailable items.
Disabling Products When Out of Stock
To disable a product once it’s sold out, you can create an observer that triggers on catalog_product_get_final_price event. Here’s how to implement this:
-
Create the Observer
- In your custom module, create a file named
Observer.php. - Implement the
executemethod:
public function execute(\Magento\Framework\Event\Observer $observer) { $product = $observer->getProduct(); if ($product->isAvailable() && $product->getQty() <= 0) { $product->setStatus(Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED); $product->save(); } } - In your custom module, create a file named
-
Configure the Event
- In your module’s
etcfolder, create a file namedevents.xml.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="catalog_product_get_final_price"> <observer name="disable_out_of_stock_products" instance="Vendor\Module\Observer" shared="false"/> </event> </config> - In your module’s
Clearing Customers’ Carts of Out-of-Stock Items
To remove unavailable products from customers’ carts, you can override the Magento_Checkout/js/view/summary/items file:
-
Override the File
- Create a new file in your theme’s JavaScript folder:
magento_checkout/js/view/summary/items.js.
define([ 'ko', 'Magento_Catalog/js/product-types' ], function (ko, productTypes) { 'use strict'; return function (config) { var items = ko.observableArray(), quoteItem = config.quoteItem, item = quoteItem.item(); if (!item || !item.product()) { return; } // Check if the product is out of stock if (item.product().getQty() <= 0) { // Remove the item from the cart config.removeItem(item); return []; } // ... rest of the code ... }; }); - Create a new file in your theme’s JavaScript folder:
-
Update the Dependencies
- Update your
requirejs-config.jsfile to include the new file:
var config = { map: { '*': { 'Magento_Checkout/js/view/summary/items': 'Vendor_Module/js/view/summary/items' } } }; - Update your
Remember, you’ll need to replace Vendor with your actual vendor name and Module with the actual module name in these examples.
Conclusion
Automatically disabling out-of-stock products and clearing customers’ carts of unavailable items are essential features for a seamless shopping experience. By implementing these solutions, you can ensure that your Magento store remains user-friendly even when facing stock issues.
For more advanced Magento customizations and development guides, I recommend checking out the comprehensive resources available at Laravel Company.
Don’t hesitate to reach out if you have any questions or need further assistance with your Magento setup. Happy coding!