How to Create Product Attribute in Magento 2 Programmatically ?
Product attributes are the properties that describe a product. In this blog, we will discuss about how we can create “Product Attribute” in Magento 2 Programmatically.
We will create the InstallData.php file at below path:
<vendor_name>\<module_name>\Setup
<?php namespace Rocktechnolabs\Blog\Setup; use Magento\Eav\Setup\EavSetup; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; class InstallData implements InstallDataInterface { private $eavSetupFactory; public function __construct(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, ‘sample_attribute’, [ ‘type’ => ‘text’, ‘backend’ => ”, ‘frontend’ => ”, ‘label’ => ‘Sample Atrribute’, ‘input’ => ‘text’, ‘class’ => ”, ‘source’ => ”, ‘global’ => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL, ‘visible’ => true, ‘required’ => true, ‘user_defined’ => false, ‘default’ => ”, ‘searchable’ => false, ‘filterable’ => false, ‘comparable’ => false, ‘visible_on_front’ => true, ‘used_in_product_listing’ => true, ‘unique’ => false, ‘apply_to’ => ” ] ); } } |
After Creating InstallData.php You need to run below basic command.
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush
php bin/magento cache:clean
You can see this custom attribute in Backend Product Page.
NOTE : If you want to display this product attribute on frontend at More Information tab the you have to set ‘visible_on_front’ as true and your custom product attribute will be displayed on frontend as Below :
Conclusion:
Using above steps, you can easily understand how to get “Product Attribute” in Magento 2 .If you have any query regarding above code implementation then you can contact us or let us know in comment section.
Recommended Read:
What are the Different Types of Products in Magento 2?