How to override function getAllowProducts()
from Magento\ConfigurableProduct\Block\Product\View\Type\Configurable.php
in magento 2.
I want to override above function but not getting changes of function and nothing display any issue.
There are no any error display inside log file.
i will share my code here,
registration.php
file,
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Test_Configuration',
__DIR__
);
etc folder,
module.xml
code is,
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Test_Configuration" setup_version="1.0.0"/>
</config>
i have override block inside
di.xml
code is
<?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\ConfigurableProduct\Block\Product\View\Type\Configurable" type="Test\Configuration\Block\Outstock" />
</config>
Block folder,
Outstock.php
file,
<?php
namespace Test\Configuration\Block;
class Outstock extends \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable
{
public function getAllowProducts()
{
if (!$this->hasAllowProducts()) {
$products = [];
$skipSaleableCheck = $this->catalogProduct->getSkipSaleableCheck();
$allProducts = $this->getProduct()->getTypeInstance()->getUsedProducts($this->getProduct(), null);
foreach ($allProducts as $product) {
$products[] = $product;
}
$this->setAllowProducts($products);
}
return $this->getData('allow_products');
}
protected function _toHtml()
{
$this->setModuleName($this->extractModuleName('Magento\ConfigurableProduct\Block\Product\View\Type\Configurable'));
return parent::_toHtml();
}
}
i havent any error display not any log generate for this file and module is activated. inside setup_module
entry are generated.
Any suggestion for override function of configurable.php
file.
Thanks.
Best Answer
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
Then Your Plugin Class should look like this:
Be sure to clear cache and also your var/generation dir to have this changes applied