Magento 2 : How to Get all User Defined Attributes in Product Model

The question:

I need to get all attributes of catalog_productentity_type_id which are user defined. I can do this via eav/config analogue in Magento 1, but how can do this in Magento2 ?

Something like this query should do:

SELECT *
FROM eav_attribute
WHERE entity_type_id = 4 AND is_user_defined = 1;

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

We should use Service Contracts Layer.

/**
 * @var MagentoFrameworkApiSearchCriteriaBuilder
 */
protected $searchCriteriaBuilder;
/**
 * @var MagentoEavApiAttributeRepositoryInterface
 */
protected $attributeRepository;


public function __construct(
    MagentoFrameworkApiSearchCriteriaBuilder $searchCriteriaBuilder,
    MagentoEavApiAttributeRepositoryInterface $attributeRepository,
    ......
)
{
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->attributeRepository = $attributeRepository;
    ......
}

In your custom method:

    $searchCriteria = $this->searchCriteriaBuilder->addFilter('is_user_defined', 1)->create();
    $attributeRepository = $this->attributeRepository->getList(
        MagentoCatalogApiDataCategoryAttributeInterface::ENTITY_TYPE_CODE,
        $searchCriteria
    );

    foreach ($attributeRepository->getItems() as $items) {
        $items->getAttributeCode();
        $items->getFrontendLabel();
    }

NOTE: For the entity type code in getList method, we can find in the eav_entity_type table.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment