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
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;
}
}
-
1Thank 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?Riccardo Ronconi– Riccardo Ronconi2018年12月22日 13:48:45 +00:00Commented Dec 22, 2018 at 13:48
-
Like afterGetPrice, will afterGetCustomAttribute work for product attribute using DI plugin?Wasim– Wasim2021年01月21日 12:45:59 +00:00Commented Jan 21, 2021 at 12:45
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
-
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 answerRiccardo Ronconi– Riccardo Ronconi2019年05月02日 09:18:04 +00:00Commented May 2, 2019 at 9:18