5

I need to get all attributes of catalog_product - entity_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;
7

We should use Service Contracts Layer.

/**
 * @var \Magento\Framework\Api\SearchCriteriaBuilder
 */
protected $searchCriteriaBuilder;
/**
 * @var \Magento\Eav\Api\AttributeRepositoryInterface
 */
protected $attributeRepository;


public function __construct(
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
    \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository,
    ......
)
{
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->attributeRepository = $attributeRepository;
    ......
}

In your custom method:

    $searchCriteria = $this->searchCriteriaBuilder->addFilter('is_user_defined', 1)->create();
    $attributeRepository = $this->attributeRepository->getList(
        \Magento\Catalog\Api\Data\CategoryAttributeInterface::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.

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.