Magento 2 : Override block file Magento\ConfigurableProduct\Block\Product\View\Type\Configurable.php

For Magento2.1 version you need to override Magento\Swatches\Block\Product\Renderer\Configurable

1) Create di.xml file in Folder Namespace\Module\etc

<?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="Namespace\Module\Block\Outstock" />
</config>

2) Create Outstock.php Block file in Folder Namespace\Module\Block

<?php 

namespace Namespace\Module\Block;

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

    public function getAllowProducts()
    {
        if (!$this->hasAllowProducts()) {
            $products = [];
            $skipSaleableCheck = $this->catalogProduct->getSkipSaleableCheck();
            $allProducts = $this->getProduct()->getTypeInstance()->getUsedProducts($this->getProduct(), null);
            foreach ($allProducts as $product) {
                if ($product->isSaleable() || $skipSaleableCheck) {
                    $products[] = $product;
                }
            }
            $this->setAllowProducts($products);
        }
        return $this->getData('allow_products');
    }


}

you don't have to override the preference and you should not.

You can easily use a Plugin to set the allow_products data before the method is called. You find a nice tutorial about plugins here:

http://alanstorm.com/magento_2_object_manager_plugin_system

To create your Plugin, you first need to add a type to your etc/frontend/di.xml

<type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable">
    <plugin name="changeAllowProductsBehaviour" type="Vendor\Module\Model\ConfigurableProduct\Block\Product\View\Type\Configurable\Plugin" sortOrder="10" />
</type>

Then Your Plugin Class should look like this:

<?php
namespace Vendor\Module\Model\ConfigurableProduct\Block\Product\View\Type\Configurable;

class Plugin
{
    /**
     * getAllowProducts
     *
     * @param \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject
     *
     * @return array
     */
    public function beforeGetAllowProducts($subject)
    {
        if (!$subject->hasData('allow_products')) {
            $products = [];
            $allProducts = $subject->getProduct()->getTypeInstance()->getUsedProducts($subject->getProduct(), null);
            foreach ($allProducts as $product) {
                    $products[] = $product;
            }
            $subject->setData('allow_products', $products);
        }

        return [];
    }

}

Be sure to clear cache and also your var/generation dir to have this changes applied


You need to override

Magento\Swatches\Block\Product\Renderer\Configurable 

instead of overriding

Magento\ConfigurableProduct\Block\Product\View\Type\Configurable 

file.