Fixing the Price Display Issue for Configurable Products in Magento 2
In Magento 2, overriding the price display behavior can be complex, especially when dealing with configurable products in the catalog view. While your current approach works perfectly for simple products, it falls short when handling configurable items. Let’s dive into the issue and provide a comprehensive solution.
Understanding the Problem
The key problem lies in how Magento renders prices for configurable products on the catalog page. Unlike simple products, which use the Catalog\Pricing\Render\FinalPriceBox class directly, configurable products utilize a different mechanism involving price aggregation and super product management.
When you override the Catalog\Pricing\Render\FinalPriceBox, it works flawlessly for simple products because Magento uses this block to render prices. However, for configurable products, Magento bypasses this block and employs the Catalog\Product\Configure\Price class instead.
The Correct Approach
To successfully override the price display for configurable products in the catalog view, you need to target the correct class responsible for rendering their prices. Here’s a step-by-step guide:
- Create the required XML file:
Open your module configuration file at app/code/Vendor/MyModule/etc/di.xml and add the following preference mapping:
<?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\Catalog\Product\Configure\Price" type="Vendor\MyModule\Block\ConfigurablePriceBox"/>
</config>
This tells Magento to replace the default Configure\Price class with your custom block.
- Implement the Custom Block:
Create a new file at app/code/Vendor/MyModule/Block/ConfigurablePriceBox.php:
namespace Vendor\MyModule\Block;
class ConfigurablePriceBox extends \Magento\Catalog\Product\Configure\Price
{
/**
* Wrap with standard required container
*
* @param string $html
* @return string
*/
protected function wrapResult($html)
{
return '-TEST-<div class="price-box ' . $this->getData('css_classes') . '" ' .
'data-role="priceBox" ' .
'data-product-id="' . $this->getSaleableItem()->getId() . '" ' .
'data-price-box="product-id-' . $this->getSaleableItem()->getId() .'"' .
'>' . $html . '</div>';
}
}
This class extends the default Configure\Price block and overrides the wrapResult method, allowing you to modify the HTML output of the price box for configurable products.
Conclusion
By following this approach, you successfully override the price display behavior for both simple and configurable products in your Magento 2 catalog view. Remember that the key is to identify and target the correct classes used by Magento for rendering prices based on the product type.
For more advanced pricing customizations, don’t forget to explore the extensive documentation available at Laravel Company’s Magento resource center.