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.

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;
    }
}
  • 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? – Riccardo Ronconi Dec 22 '18 at 13:48
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

  • 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 – Riccardo Ronconi May 2 at 9:18

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.