How to override _registerJsPrice($price) function in Configurable.php Block in Magento2?
-
10-10-2020 - |
Question
I am trying to override __registerJsPrice($price) function in configurable.php
This function is work when we change swatch.
Path of configurable.php is /opt/lampp/htdocs/magento/vendor/magento/module-configurable-product/Block/Product/View/Type
This is Protected function. so I overrided using preference method
Step 1:- create di.xml file in Folder app/code/Webkul/Hello/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\ConfigurableProduct\Block\Product\View\Type\Configurable" type="Webkul\Hello\Block\Rewrite\Product\Configurable" />
</config>
Step 2:-create Configurable.php Block file in Folder /magento/app/code/Webkul/Hello/Block/Rewrite/Product
<?php
namespace Webkul\Hello\Block\Rewrite\Product;
class Configurable extends \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable
{
protected function _registerJsPrice($price)
{
return str_replace(',', '.', $price + 11);
}
}
I Change return str_replace(',', '.', $price); to return str_replace(',', '.', $price + 11); it mean when i change swatch the price increase by +11 rupees.
I changed this in the core file and the changes were shown but when I override at that time no any charges shown.
Solution
Step 1:- create di.xml file in Folder app/code/Webkul/Hello/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="Webkul\Hello\Block\Rewrite\Product\Configurable" />
</config>
Step 2:-create Configurable.php Block file in Folder /magento/app/code/Webkul/Hello/Block/Rewrite/Product
<?php
namespace Webkul\Hello\Block\Rewrite\Product;
class Configurable extends \Magento\Swatches\Block\Product\Renderer\Configurable
{
protected function _registerJsPrice($price)
{
return str_replace(',', '.', $price + 11);
}
}