Magento 2.1.6 Configurable Product – Display Swatches When Out of Stock

configurable-productmagento2.1.6products

I have a configurable products with few sizes, let's say : 123, 160, M, S, L, XL

When I put products M and S on qty 0, which means it is out of stock, then sizes disappear form the swatches option.

I was expected to see also out of stock products with a special class and to be non clickable, but out of stock products disappear.

I found a solution and I will post my answer. Maybe that will help someone.

Best Answer

To solve this issue:

Step 1

I installed this module( for some other versions of magento maybe this will work without step 2)

https://github.com/mjankiewicz/MagentoConfigurableProduct

Step 2

Create a module with:

etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Swatches\Block\Product\Renderer\Configurable" type="Vendor\Namespace\Block\Outstock" />
</config>

then create Block/Outstock.php

<?php 

namespace vendor\namespace\Block;

class Outstock extends \Magento\Swatches\Block\Product\Renderer\Configurable
{

   public function getAllowProducts()
    {
        if (!$this->hasAllowProducts()){
             $skipSaleableCheck = 1;
             $products = $skipSaleableCheck ?
             $this->getProduct()->getTypeInstance()->getUsedProducts($this->getProduct(), null) :
                $this->getProduct()->getTypeInstance()->getSalableUsedProducts($this->getProduct(), null);
            $this->setAllowProducts($products);
        }
        return $this->getData('allow_products');
    }
}

After this run

php bin/magento setup:upgrade 

php bin/magento cache:clean

php bin/magento cache:flush

Of course that you can combine those 2 modules. You can take /Helper/Data.php form the first module JanSoft_ConfigurableProduct and put this into the second module, or the oposite.

Related Topic