2

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
4
  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)
  • Important note to 2: If the attribute doesn't exists a NoSuchEntityException is thrown and Magento creates the attribute. – Michael Poppinger May 22 at 11:27
4

You can inject Magento\Eav\Model\Config object and use the getAttribute('catalog_product', $attributecode) function to check if your custom eav attribute with code $attributecode already exist or not.

Here is the code sample:

$attribute = $this->eavConfig->getAttribute($entityTypeCode, $attributeCode);
if (!$attribute || !$attribute->getAttributeId()) {
    throw new NoSuchEntityException(
        __('Attribute with attributeCode "%1" does not exist.', $attributeCode)
    );
}
return $attribute;
0

Check "eav_entity_type" table. It will show you all the attribute type code you can use while fetching the information.

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.