Magento 2: Issue when creating Magento Plugin for overriding GetSelectionTitlePrice method
-
10-03-2021 - |
Question
I 've created the following plugin to override a method located at
vendor/magento/module-bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
but it still does not seem to sort the desired effect. Any ideas on how this could work as desired?
app/code/MySpace/MyModule/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option">
<plugin name="bundle-product-option-radio" type="MySpace\MyModule\Plugin\RadioPlugin" />
</type>
</config>
app/code/MySpace/MyModule/Plugin/RadioPlugin.php
<?php
namespace MySpace\MyModule\Plugin;
class RadioPlugin
{
public function aroundGetSelectionQtyTitlePrice(
\Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option $subject,
\Closure $proceed,
$selection,
$includeContainer = true)
{
$this->setFormatProduct($selection);
$priceTitle = '<span class="product-name">'
. $this->escapeHtml($selection->getName())
. '</span>';
return $priceTitle;
}
}
The method to override is located at vendor/magento/module-bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
:
/**
* Get bundle option price title.
*
* @param \Magento\Catalog\Model\Product $selection
* @param bool $includeContainer
* @return string
*/
public function getSelectionQtyTitlePrice($selection, $includeContainer = true)
{
$this->setFormatProduct($selection);
$priceTitle = '<span class="product-name">'
. $selection->getSelectionQty() * 1
. ' x '
. $this->escapeHtml($selection->getName())
. '</span>';
$priceTitle .= ' ' . ($includeContainer ? '<span class="price-notice">' : '') .
'+' .
$this->renderPriceString($selection, $includeContainer) . ($includeContainer ? '</span>' : '');
return $priceTitle;
}
Solution
I think you should use $subject instead of $this in function block to refer Core class object.
public function aroundGetSelectionQtyTitlePrice(
\Magento\Bundle\Block\Catalog\Product\View\Type\Bundle\Option $subject,
\Closure $proceed,
$selection,
$includeContainer = true)
{
$subject->setFormatProduct($selection);
$priceTitle = '<span class="product-name">'
. $subject->escapeHtml($selection->getName())
. '</span>';
return $priceTitle;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange