I load some related products inside a foreach and want to call some attribute values of these individual products.
My current code below works fine with using $objectManager, but that's not the best way to handle this.
How can I get the value of the product attribute, without using the $objectManager ?
Code Helper/Data:
<?php
namespace MyModule\LinkedProducts\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
\MagePal\LinkProduct\Model\Accessory $accessory,
\Magento\Catalog\Block\Product\AbstractProduct $abstractProduct
) {
$this->accessory = $accessory;
$this->abstractProduct = $abstractProduct;
}
public function getLinkedProducts()
{
$product = $this->abstractProduct->getProduct();
return $this->accessory->getAccessoryProducts($product);
}
}
Code phtml:
<?php $linkedproducts = $this->helper('MyModule\LinkedProducts\Helper\Data');
$relatedProducts = $linkedproducts->getLinkedProducts();?>
<?php foreach ($relatedProducts as $relatedProduct) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->create('Magento\Catalog\Model\Product')->load($relatedProduct->getId());
echo $_product->getData('my_attribute_value');
}?>