
Magento 2.x – How to add a new product custom attribute programmatically
One of the most popular operations that we will need on Magento, is adding a custom attribute to our catalog products. To do so, basically, we will need to perform the following steps:
- Create a new module
- Create an InstallData script
- app/code/Offset101/ProductAttributeExample/Setup/InstallData.php:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758<?phpnamespace Offset101\ProductAttributeExample\Setup;use Magento\Framework\Setup\InstallDataInterface;use Magento\Framework\Setup\ModuleContextInterface;use Magento\Framework\Setup\ModuleDataSetupInterface;/*** Class InstallData* @package Offset101\ProductAttributeExample\Setup*/class InstallData implements InstallDataInterface{/*** @var \Magento\Eav\Setup\EavSetupFactory*/private $eavSetupFactory;/*** InstallData constructor.* @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory*/public function __construct(\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory){$this->eavSetupFactory = $eavSetupFactory;}public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context){$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);$eavSetup->addAttribute(\Magento\Catalog\Model\Product::ENTITY,'canonical_path_url',['type' => 'text','backend' => '','frontend' => '','label' => 'Canonical Path URL','input' => 'text','class' => '','global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,'visible' => true,'required' => false,'user_defined' => false,'default' => '','searchable' => false,'filterable' => false,'comparable' => false,'visible_on_front' => false,'used_in_product_listing' => true,'unique' => false,'apply_to' => '']);}} - We can optionally add the following:
- ‘source’ : A Source model to provide a list of options. We will need to write the method “getAllOptions”.
- ‘backend’: A backend model to allow you to perform certain actions when an attribute is loaded or saved. ie: a validation. We will need to write the method validate(Object).
- ‘frontend’: A frontend model to define how it should be rendered on the frontend. We will need to write method getValue(Object).
- app/code/Offset101/ProductAttributeExample/Setup/InstallData.php:
- Execute the InstallData script and verify that it works
12cd <magento2_root>php bin/magento setup:upgrade- After running this, the new attribute should have been added to the database. You can check the eav_attribute and catalog_eav_attribute tables to verify that the attribute and its properties are there.
- If the attribute is there, but you need to change something, or re-run your script, you can easily remove the row of your script (or downgrade the version) on the setup_module table.
For more information, you can follow up the following link: How to Add a New Product Attribute