2

I want to retrieve the collection of all product attributes so that I can have all the details of an attribute.

Anyone who can help me please let me know.

4

I have tried all the almost all the options which I get on internet, but none of them have fulfilled my requirement. And finally I got solution, SO I am posting this answer so that it can be usefull for others also.

use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory;

Your Class Name
{   
    protected $_collectionFactory;
    public function __construct(
        ....
        CollectionFactory $collectionFactory,
        ....
    ) {
        $this->_collectionFactory = $collectionFactory;
        ....
    }

    public function getAttributes()
    {
        $collection = $this->_collectionFactory->create();
        $attr_groups = array();
        foreach ($collection as $items) {
            $attr_groups[] = $items->getData();
        }
        return $attr_groups; //This will give you the collection of all the attributes which are available in that magento instance
    }
}

I hope this will solve the queries similar to me.

0

1. app/code/Test/HelloWorld/Block/HelloWorld.php

<?php
namespace Test\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }

    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3); // fetching only 3 products
        return $collection;
    }
}
?>

2. Display product collection in phtml file

$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

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.