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.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI 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.
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>";
}