Question

Sorry in advance if this is a silly question. I'm fairly new to backend development.

I have a custom attribute that determines whether or not a price should be visible on the frontend. It works just fine with simple products, but I can't get it to work with grouped products, since it doesn't seem that Magento loads the associated simple products as objects in the template file. As a result, I can't access the values of custom attributes.

Here's that part of the template file:

$product = $block->getSaleableItem();

if (!$product->getData(\Vendor\Pricing\Helper\Data::ATTRIBUTE_PRICING_VISIBLE)) {
    return '';
}

When this runs for grouped products, getData always returns 0/No even if ATTRIBUTE_PRICING_VISIBLE = Yes. When I try something like getCustomAttribute instead of getData, it returns a null value. Additionally, I tried getResource and got the error "Trying to get property of non-object."

To get the full product to load, I tried the Product Factory method, like so:

<?php

namespace Vendor\Fixes\MagentoCatalog\Plugin\Block;

class Product extends \Magento\Framework\View\Element\Template {

  protected $_productloader;  

  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {

        $this->_productloader = $_productloader;
        parent::__construct($context);
    }

    public function getLoadProduct($id) {
        return $this->_productloader->create()->load($id);
    }

} 

.phtml file:

$productId = $block->getSaleableItem()->getId();
$product = $block->getLoadProduct($productId);

if (!$product->getData(\Vendor\Pricing\Helper\Data::ATTRIBUTE_PRICING_VISIBLE)) {
    return '';
}

But this also returns a null error when trying to access that attribute. The only thing that seems to work is Object Manager, which I know is a huge no-no. This is the code that works:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productId = $block->getSaleableItem()->getId();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);

<?php if (!$product->getData(\Vendor\Pricing\Helper\Data::ATTRIBUTE_PRICING_VISIBLE)) {
    return '';
} ?>

So how can I accomplish this without the use of Object Manager? Thanks in advance for your help!

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top