Plugin isn't working in Magento2 local host
-
22-01-2021 - |
Question
My very basic plugin is not working and i can't understand why. I'm very new to Magento 2 so it's probably something simple. The Plugin is suppose to display "Too expensive" or "too cheap" on all products.
di.xml code
<config>
<type name="Inchoo\Custom\Plugins">
<plugin name="Product" type="Inchoo\Custom\Plugins\Product" sortOrder="1"
disabled="false"/>
</type>
</config>
Product.php code
<?php
namespace Inchoo\Custom\Plugins;
Class Product {
public function aftergetName(\Magento\Catalog\Model\Product $product, $name)
{
$price = $product ->getData(key:'price');
if ($price < 60 ) {
$name .= " So cheap" ;
}
else {
$name .= " Too expensive";
}
return $name;
}
}
Any help would be much appreciated. Thanks in advance, Greg
La solution
You di.xml file should have below code:
<?xml version="1.0"?>
<config>
<type name="Magento\Catalog\Model\Product">
<plugin name="InchooProduct" type="Inchoo\Custom\Plugins\Product" sortOrder="1"
disabled="false"/>
</type>
</config>
- Type name: A class, interface, or virtual type, which is observed by a plugin.
- Plugin name: A plugin name.
Plugin type: The name of a plugin’s class or virtual type.
Plugin sortOrder: Order, in which the plugins calling the same method are to be executed.
Plugin disabled: This attribute defines whether the plugin is enabled or not. disabled="true" defines the plugin is disabled.
change your function name aftergetName
to afterGetName
Autres conseils
The method name needs to be afterGetName
. Also getData(key:'price')
is wrong. You can either use ->getData('price')
or ->getPrice()
.
<?php
namespace Inchoo\Custom\Plugins;
Class Product {
public function afterGetName(\Magento\Catalog\Model\Product $product, $name)
{
$price = $product->getPrice();
if ($price < 60 ) {
$name .= " So cheap" ;
}
else {
$name .= " Too expensive";
}
return $name;
}
}
See if that works.