I want to check if product attribute with same code already exists in setup file of my custom module?
How I could check it?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI want to check if product attribute with same code already exists in setup file of my custom module?
How I could check it?
Try this:
Note: $eavSetupFactory should be an instance of Magento\Eav\Setup\EavSetupFactory class, so add it to your constructor as a dependency.
/** @var Magento\Eav\Setup\EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
if(!$eavSetup->getAttributeId(\Magento\Catalog\Model\Product::ENTITY, 'attr_code')) {
//Create the attribute
}
This will attempt to retrieve the attribute ID for the attribute with the code attr_code
. If it returns a falsey value, the attribute does not exist.
// use Magento\Eav\Api\AttributeRepositoryInterface;
/**
* Installs data for a module
*
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
* @return void
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
if (version_compare($context->getVersion(), '1.0.0', '<')) {
try {
$this->attributeRepository->get(
Product::ENTITY,
self::SPECIAL_MEASURE_MESSAGE_ATTRIBUTE_CODE
);
} catch (NoSuchEntityException $e) {
$this->eavSetup->addAttribute(
Product::ENTITY,
self::SPECIAL_MEASURE_MESSAGE_ATTRIBUTE_CODE,
[
'type' => 'varchar',
'input' => 'textarea',
'label' => 'Special Measure Message',
'required' => false,
'group' => 'General',
'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
'is_used_in_grid' => true,
'user_defined' => false,
'visible' => true,
'used_in_product_listing' => true,
]
);
}
}
}
since \Magento\Framework\Setup\ModuleDataSetupInterface
$setup does not contain a getAttributeId()
method you always need to call the attributeRepository to get the attribute