0

I have created Products attribute name as Electronics, I want to call that attribute in my HomePage which is homepage.phtml I don't know how to do that, please help me. Thanks A lot.

1 Answer 1

0

object method

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
echo $product->getElectronics();

Factory Method

<?php
namespace Meetanshi\Module\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 code

$product=$this->getLoadProduct(20);
echo $product->getElectronics();

In Magento 2.1

      public function __construct(
        \Magento\Framework\App\Action\Context $context,
        ProductRepositoryInterface $productRepository
      ) {
          parent::__construct($context);

          $this->productRepository = $productRepository;
      }
      public function getProduct($productId)
      {
         return $product = $this->productRepository->getById($productId);
      }
  }

In phtml file

$data=$block->getProduct(Product_id);
echo $data->getElectronics();

Thanks

12
  • Could you please tell me where to keep object method,factory method and all?
    – Ayaz
    Nov 22, 2017 at 10:39
  • These three are the different methods. You can use first one object method and use it in homepage.phtml file.
    – Meetanshi
    Nov 22, 2017 at 10:47
  • The code which you have given me above is for Magento1.x or Magento2.x? I've tried it for magento 2.x but it is not working. Getting error as : We're sorry, an error has occurred while generating this content.
    – Ayaz
    Nov 22, 2017 at 12:17
  • can you please share homepage.phtml file? Its for Magento 2
    – Meetanshi
    Nov 22, 2017 at 12:45
  • <div class="main_bottom_right"> <div class="right_cont"> <h3 class="right_title_gift"><span><span>Electronics</span></span></h3> <!-- Beth h3 --> <div class="best_week"> <ul class="products-grid"> here I want to call the attribute </ul> </div> </div> </div>
    – Ayaz
    Nov 23, 2017 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.