0

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;
    }
}

enter image description here

Any help would be much appreciated. Thanks in advance, Greg

2

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

  • All sorted, cheers! – Greg Aug 13 '18 at 16:25
1

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.

  • updated my answer . – Chris Anderson Aug 13 '18 at 16:18
  • Cheers, all sorted now. Thanks for your help! – Greg Aug 13 '18 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.