Magento 2 – How to Get All Attributes in Source Model

magento2source-model

I am using a source model for fields of the configuration.
I want to get all product attributes (no matter the product or the attribute set) in this source model.

Best Answer

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

Magento\Eav\Model\Entity\Attribute;

pass the AttributeCollectionFactory to your constructor.

ex :

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $attributecollectionFactory

              .
              .
              .
     //other arguments
    ) {
        $this->attributeCollectionFactory = $attributecollectionFactory;
    }

and add this function.

 protected function getAllAttributes()
    {
        $attributeCollection = $this->attributecollectionFactory->create();

        /**
         * If you want only filterable attributes.
         * and add filters as per your requirement.
         */
        $attributeCollection->addIsFilterableFilter();

        return $attributeCollection->getItems();
    }