1

Hello Everyone :) I'm in a bit of an empasse now: I'm building a module to edit the price of products that have a custom attribute by multiplying their weight by a variable. Now, almost everything works, except I can't seem to understand how to reference the products' attributes inside a plugin...

This is the code of my Plugin:

namespace Namespace\Module\Plugin; class Product { public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result) { $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product'); if($product->getData('has_attribute_x')) { $wbtweight = $product->getWeight(); $helper = $this->helper('Namespace\Module\Helper\Data'); $wbtvalue = $helper->getConfig('stuff/stuff/variable'); $wbtfinal = $wbtweight * floatval($wbtvalue); return $result + $wbtfinal; } } }

But, when I run it, I get an Uncaught Exception saying that I called getData on null, so... I don't seem to understand how Plugins work, I mean don't they act on every instance of a product (sort of like a foreach)? I haven't found a very explanatory dev documentation on this kind of issues... Thanks in advance for the help.

2 Answers 2

0

Try following way:

 use Namespace\Module\Helper\Data as YourHelper; class Product { /** * @var YourHelper */ private $yourHelper; /** * Product constructor. * * @param YourHelper $yourHelper */ public function __construct( YourHelper $yourHelper ) { $this->yourHelper = $yourHelper; } public function afterGetPrice( \Magento\Catalog\Model\Product $subject, $result ) { if($subject->getData('has_attribute_x')) { $wbtweight = $subject->getWeight(); $wbtvalue = $this->yourHelper->getConfig('stuff/stuff/variable'); $wbtfinal = $wbtweight * floatval($wbtvalue); return $result + $wbtfinal; } return $result; } } 
2
  • 1
    Thank you for the answer, the error is gone, but it still doesn't calculate neither the weight nor the condition. It seems like the problem is still getData, that always returns 0... Any clue? Commented Dec 22, 2018 at 13:48
  • Like afterGetPrice, will afterGetCustomAttribute work for product attribute using DI plugin? Commented Jan 21, 2021 at 12:45
0

If you cannot get your custom attribute data => try to load the product again :3

And you may want to use this event to change the price: catalog_product_get_final_price

1
  • Actually, I forgot to accept the previous answer, but that did work, eventually. Thank you very much for answering and reminding me to accept the answer Commented May 2, 2019 at 9:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.