Magento 2 – Get Custom Attribute of a Single Product Inside a Plugin

custom-attributesmagento2plugin

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.

Best Answer

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