Magento 2 – How to Check if Custom Product Attribute Exists

attributescustom-attributesmagento2product-attribute

I want to check if my custom product attributes exist before I attempt to utilize it in any way. Whats the best way to check it in Magento 2.

Note that I don't want to check if specific product has the attribute. I want to check if that attribute exists in Magento.

I've found partial answer on stackexchange https://magento.stackexchange.com/a/107993/14809

but that answer is very limited. Especially the code example is very scarce:

try {
   $attribute = $this->attributeRepository->get($entityType, $attributeCode);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
    //  attribute is not exists
}
  1. It's not clear what to enter in $entityType.
  2. What will get return if the attribute does not exist?
  3. I don't know where to find example implementation of the methods (e.g. get(...)) defined in the interface \Magento\Eav\Api\AttributeRepositoryInterface.php

Best Answer

  1. $entityType in your case is the 'catalog_product' as its a product attribute
  2. It will throw an exception
  3. vendor/magento/module-eav/Model/AttributeRepository.php and check the public function get($entityTypeCode, $attributeCode)
Related Topic